githttp-fs 1.10.1

A git-backed content management database served over HTTP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
// githttp-fs
//
// Git-based Content Management System
// Copyright: 2026, Valerian Saliou <valerian@valeriansaliou.name>
// License: Mozilla Public License v2.0 (MPL v2.0)

//! File CRUD routes: listing, read, existence check, write, delete, move, and
//! reorder (a file's position in its parent directory's order index — the one
//! route here that writes an order index rather than a file).
//!
//! See `routes/mod.rs` for the shared handler shape (validate → lock →
//! blocking git op → hook enqueue → maintenance arm) that every write
//! handler here follows.

use axum::{
    extract::{Path, Query, State},
    http::StatusCode,
    response::IntoResponse,
    Json,
};
use chrono::{DateTime, Utc};
use serde::{de::DeserializeOwned, Deserialize};
use serde_json::{json, Value};

use std::collections::HashSet;

use crate::{
    error::AppError,
    git,
    hooks::HookJob,
    order,
    routes::AuthorRequest,
    seek::{SeekBody, SeekFilter, SeekOptions},
    state::AppState,
    util::run_blocking,
    validate,
};

/// Query parameters for the listing endpoint. All optional: the bare
/// endpoint returns page 1 of the full recursive tree.
#[derive(Deserialize)]
pub struct ListFilesQuery {
    /// Folder to root the listing at (e.g. `/docs`); repo root if omitted.
    pub prefix_path: Option<String>,
    /// How many directory levels to descend from the listing root; full
    /// recursion if omitted.
    pub maximum_depth: Option<u32>,
    /// When true, hidden entries (names starting with `.`, per the Unix
    /// convention) are included in the listing; excluded if omitted or false.
    pub include_hidden_files: Option<bool>,
    /// When set, narrows the listing to files *and directories* whose leaf
    /// name begins with the given prefix(es), compared case-insensitively (a
    /// matched directory brings its subtree along). Accepts either a bare
    /// string (a single prefix) or a JSON-array string of prefixes, e.g.
    /// `["intro", "readme"]` — an entry matches if its leaf name begins with
    /// *any* of them. Empty is rejected (`400`).
    pub file_name_starts_with: Option<String>,
    /// Lower bound (inclusive) of the created/updated date-range filter, as an
    /// RFC 3339 date-time (e.g. `2026-06-16T10:00:00Z`).
    pub include_date_from: Option<String>,
    /// Upper bound (exclusive) of the created/updated date-range filter, as an
    /// RFC 3339 date-time.
    pub include_date_to: Option<String>,
    /// Which date the range applies to: `updated` (default) or `created`.
    /// Its value is always validated, but the filter is only active — and the
    /// history walk only paid for — when at least one bound is set.
    pub include_date_type: Option<String>,
    /// When true, every level of the listing is ordered by the stored order
    /// index of the directory it belongs to; unlisted entries follow in the
    /// ordinary order. Defaults to false, so no existing caller's results
    /// change — and so the per-directory index reads it costs are only paid
    /// for by callers that want them.
    pub apply_order_index: Option<bool>,
    /// The index an entry the order index does not name is treated as holding,
    /// so unordered entries can be placed *among* the ordered ones instead of
    /// behind them: `0` (or any negative value) lifts them above every ordered
    /// entry, `2` slots them between the index's second and third entries. Left
    /// unset, unlisted entries follow the ordered ones, as they always have.
    /// Only meaningful together with `apply_order_index=true`; passing it alone
    /// changes nothing.
    pub implicit_order_default_index: Option<i64>,
    pub page: Option<usize>,
    pub per_page: Option<usize>,
}

// Pagination bounds shared with the commits endpoint: a generous default,
// and a hard cap so a caller cannot request unbounded response sizes.
const DEFAULT_PER_PAGE: usize = 100;
const MAX_PER_PAGE: usize = 500;

/// Query parameters for the count endpoint. All optional: the bare endpoint
/// counts the full recursive tree. The first three carry the exact
/// semantics of their `ListFilesQuery` namesakes.
#[derive(Deserialize)]
pub struct CountFilesQuery {
    /// Folder to root the count at (e.g. `/docs`); repo root if omitted.
    pub prefix_path: Option<String>,
    /// How many directory levels to descend from the count root; full
    /// recursion if omitted.
    pub maximum_depth: Option<u32>,
    /// When true, hidden entries (names starting with `.`, per the Unix
    /// convention) are included in the count; excluded if omitted or false.
    pub include_hidden_files: Option<bool>,
    /// A JSON array of file extensions as a string (query parameters are
    /// strings), e.g. `["md", "mdx"]`; when set, only files carrying one of
    /// these extensions are counted. Omitted: every file counts.
    pub restrict_file_extensions: Option<String>,
}

/// Body of the batch read endpoint: the entries to read, plus an optional
/// seek window applied to every file that does not carry its own (see
/// `seek.rs` for the field formats).
#[derive(Deserialize)]
pub struct BatchReadFilesRequest {
    pub files: Vec<BatchReadFileRequest>,
    pub seek: Option<SeekBody>,
}

/// One entry of the batch read `files` array: either a bare path string,
/// or an object holding the path plus an optional per-file seek window.
/// When the per-file `seek` is set it *replaces* the request-level `seek`
/// for that file (no field-by-field merge).
#[derive(Deserialize)]
#[serde(untagged)]
pub enum BatchReadFileRequest {
    Path(String),
    Options {
        path: String,
        seek: Option<SeekBody>,
    },
}

impl BatchReadFileRequest {
    /// The raw path and optional per-file seek, whichever spelling was used.
    fn parts(&self) -> (&str, Option<&SeekBody>) {
        match self {
            Self::Path(path) => (path, None),
            Self::Options { path, seek } => (path, seek.as_ref()),
        }
    }
}

/// Query parameters for the existence endpoint.
#[derive(Deserialize)]
pub struct FileExistsQuery {
    /// When true, a path resolving to a folder counts as existing too, so the
    /// endpoint answers "is there anything at this path" rather than "is there
    /// a file at this path". Defaults to false — folders stay invisible.
    pub check_prefix_path: Option<bool>,
}

#[derive(Deserialize)]
pub struct WriteFileRequest {
    pub author: AuthorRequest,
    pub content: String,
    pub message: Option<String>,
}

#[derive(Deserialize)]
pub struct DeleteFileRequest {
    pub author: AuthorRequest,
    pub message: Option<String>,
    /// When true and the path resolves to a folder, the deletion recurses over
    /// every file beneath it, in one commit. Defaults to false, in which case
    /// a folder path is simply "not a file" and answers `404` — so this heavy,
    /// destructive mode can never be entered by accident.
    ///
    /// Lives in the body rather than the query string because it changes *what
    /// the write does*, alongside `author` and `message`, instead of shaping a
    /// read.
    pub allow_prefix_path_recurse: Option<bool>,
}

#[derive(Deserialize)]
pub struct MoveFileRequest {
    pub author: AuthorRequest,
    pub destination: String,
    pub message: Option<String>,
    /// When true and the source path resolves to a folder, the whole subtree
    /// is relocated under `destination`, in one commit. Same default and same
    /// rationale for living in the body as its `DeleteFileRequest` namesake.
    pub allow_prefix_path_recurse: Option<bool>,
}

#[derive(Deserialize)]
pub struct ReorderFileRequest {
    pub author: AuthorRequest,
    /// Where the entry should sit in its parent directory's order index,
    /// zero-based, counted against the index's other entries. Must be a number;
    /// a position past the end of the index is clamped to the tail.
    ///
    /// `-1` is the one accepted negative value and means the opposite: drop the
    /// entry from the index, leaving it implicitly ordered again. It is the
    /// value the read route reports for an unlisted file, so what a caller reads
    /// back is what it can send.
    pub position: i64,
    /// Where the siblings the index does not name yet are folded in when it is
    /// materialised, carrying the listing parameter's meaning exactly: unset
    /// leaves them behind everything the index lists, `0` (or any negative
    /// value) lifts them above it, `2` slots them between the index's second and
    /// third entries.
    ///
    /// A caller reordering inside a rendered listing passes the same value it
    /// rendered with, and the index it gets back pins what it was looking at.
    /// Inert with `position: -1`, which materialises nothing.
    pub implicit_order_default_index: Option<i64>,
    /// Whether the index materialised around the positioned entry may hold
    /// dot-prefixed (hidden) siblings. Defaults to false, which keeps them out
    /// of the generated index — the same judgement `include_hidden_files=false`
    /// makes on a listing, and the right default for an index the server
    /// generates rather than one the caller dictates entry by entry.
    ///
    /// It becomes **required** (as `true`) when the positioned entry is itself
    /// hidden: pinning a dot-file has to be asked for, and asking for it
    /// through the same flag that decides its siblings' fate keeps one answer
    /// per request. `_implicit_` names what it governs — the entries folded in
    /// implicitly — which is also why it is inert with `position: -1`, where
    /// nothing is materialised.
    pub implicit_allow_hidden_files: Option<bool>,
    pub message: Option<String>,
    /// When true, the path may name a folder instead of a file, giving the
    /// folder itself a position among its siblings. Defaults to false — only
    /// files are positionable, and a folder path is then simply "not a file" and
    /// answers `404`.
    ///
    /// Lives in the body for the same reason as its `DeleteFileRequest` and
    /// `MoveFileRequest` namesakes: it changes *what the write does*, alongside
    /// `author`, `position` and `message`, rather than shaping a read. It is
    /// named without their `_recurse` suffix because nothing here recurses — a
    /// folder's position is one entry in one index, exactly as a file's is, and
    /// the folder's own contents are untouched.
    pub allow_prefix_path: Option<bool>,
}

/// Decodes the `file_name_starts_with` query value into its list of prefixes.
/// A value that looks like a JSON array (its first non-whitespace character is
/// `[`) must be a valid JSON array of strings; any other value is taken
/// verbatim as a single prefix — the original bare-string spelling, kept for
/// backward compatibility. Empty arrays and empty prefixes are rejected with
/// `400`: an empty prefix would match every entry (indistinguishable from
/// omitting the parameter), an empty array none — both only caller bugs.
fn parse_file_name_prefixes(raw: &str) -> Result<Vec<String>, AppError> {
    let prefixes = if raw.trim_start().starts_with('[') {
        serde_json::from_str::<Vec<String>>(raw).map_err(|_err| AppError::InvalidOperation {
            reason:
                "file_name_starts_with must be a string or a JSON array of strings, e.g. [\"intro\", \"readme\"]"
                    .to_string(),
        })?
    } else {
        vec![raw.to_string()]
    };

    if prefixes.is_empty() {
        return Err(AppError::InvalidOperation {
            reason: "file_name_starts_with must contain at least one prefix".to_string(),
        });
    }

    if prefixes.iter().any(|prefix| prefix.is_empty()) {
        return Err(AppError::InvalidOperation {
            reason: "file_name_starts_with must not be empty".to_string(),
        });
    }

    Ok(prefixes)
}

/// Parses a single RFC 3339 date-time query value into UTC, mapping any
/// malformed value to a `400` naming the parameter (strict validation — only
/// the RFC 3339 spelling is accepted).
fn parse_rfc3339(raw: &str, parameter: &str) -> Result<DateTime<Utc>, AppError> {
    DateTime::parse_from_rfc3339(raw)
        .map(|date_time| date_time.with_timezone(&Utc))
        .map_err(|_err| AppError::InvalidOperation {
            reason: format!(
                "{} must be an RFC 3339 date-time, e.g. 2026-06-16T10:00:00Z",
                parameter
            ),
        })
}

/// Builds the optional created/updated date-range filter from the three query
/// parameters. `include_date_type` is validated strictly whenever present
/// (only `updated` or `created`, defaulting to `updated`), but the filter is
/// left inactive — so the listing keeps its cheap tree-only fast path and no
/// commit history is walked — unless at least one date bound is given. When
/// both bounds are present, `from` must be strictly before `to` (the window
/// is `[from, to)`, so equal bounds would select nothing).
fn parse_date_filter(
    from: Option<&str>,
    to: Option<&str>,
    date_type: Option<&str>,
) -> Result<Option<git::DateFilter>, AppError> {
    let kind = match date_type {
        None | Some("updated") => git::DateKind::Updated,
        Some("created") => git::DateKind::Created,
        Some(other) => {
            return Err(AppError::InvalidOperation {
                reason: format!(
                    "include_date_type must be 'updated' or 'created': {}",
                    other
                ),
            })
        }
    };

    let from = from
        .map(|raw| parse_rfc3339(raw, "include_date_from"))
        .transpose()?;
    let to = to
        .map(|raw| parse_rfc3339(raw, "include_date_to"))
        .transpose()?;

    // No bound set: the type is validated but the filter stays inactive, so
    // the listing avoids the history walk entirely.
    if from.is_none() && to.is_none() {
        return Ok(None);
    }

    if let (Some(from), Some(to)) = (from, to) {
        if from >= to {
            return Err(AppError::InvalidOperation {
                reason: "include_date_from must be strictly before include_date_to".to_string(),
            });
        }
    }

    Ok(Some(git::DateFilter { from, to, kind }))
}

/// GET /:collection_id/:tenant_id/files
/// Returns the repository contents as a recursive file tree.
/// Accepts an optional `prefix_path` query parameter (e.g. `?prefix_path=/docs`) to scope
/// the listing to a specific sub-directory. The path must be a folder and must
/// not escape the repository root (`..' components are rejected).
///
/// Pagination is *parent-based*: `page`/`per_page` window over the
/// root-level entries of the listing, each carrying its full subtree.
/// Combined with `maximum_depth` this lets clients bound response size on
/// arbitrarily large repositories.
pub async fn list_files(
    State(state): State<AppState>,
    Path((collection_id, tenant_id)): Path<(String, String)>,
    Query(query): Query<ListFilesQuery>,
) -> Result<impl IntoResponse, AppError> {
    let collection_id = validate::collection_id(&collection_id)?.to_string();
    let tenant_id = validate::tenant_id(&tenant_id)?.to_string();

    // An empty sanitised prefix ("/" or "") means "repo root", which is the
    // same as no prefix at all — normalise it to None here so the git layer
    // only ever sees a meaningful prefix.
    let path_prefix: Option<String> = query
        .prefix_path
        .as_deref()
        .map(validate::folder_path)
        .transpose()?
        .filter(|p| !p.is_empty())
        .map(|p| p.to_string());

    // maximum_depth=0 would mean "list nothing", which is more likely a
    // caller bug than an intent — reject it explicitly.
    let maximum_depth: Option<usize> = match query.maximum_depth {
        Some(0) => {
            return Err(AppError::InvalidOperation {
                reason: "maximum_depth must be at least 1".to_string(),
            })
        }
        Some(d) => Some(d as usize),
        None => None,
    };

    let include_hidden_files = query.include_hidden_files.unwrap_or(false);

    // Accepts either a bare string (a single prefix) or a JSON-array string
    // of prefixes (query parameters are strings, so an array travels the same
    // way `seek_from_line_starts_with` does), so several prefixes can be
    // searched at once — an entry matches if its leaf name begins with *any*
    // of them.
    let file_name_starts_with: Option<Vec<String>> = query
        .file_name_starts_with
        .as_deref()
        .map(parse_file_name_prefixes)
        .transpose()?;

    let date_filter = parse_date_filter(
        query.include_date_from.as_deref(),
        query.include_date_to.as_deref(),
        query.include_date_type.as_deref(),
    )?;

    // The options object *is* the opt-in: absent, the git layer does not read a
    // single index. `implicit_order_default_index` is inert on its own, exactly
    // as `include_date_type` is without a date bound.
    let order_options: Option<git::OrderOptions> = query
        .apply_order_index
        .unwrap_or(false)
        .then_some(git::OrderOptions {
            implicit_default_index: query.implicit_order_default_index,
        });

    let page = query.page.unwrap_or(1).max(1);
    let per_page = query
        .per_page
        .unwrap_or(DEFAULT_PER_PAGE)
        .clamp(1, MAX_PER_PAGE);

    tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, path_prefix = ?path_prefix, maximum_depth = ?maximum_depth, include_hidden_files = include_hidden_files, file_name_starts_with = ?file_name_starts_with, date_filter = ?date_filter, order_options = ?order_options, page = page, per_page = per_page, "handling list files request");

    let repo_path = state
        .config
        .server
        .repos_path
        .join(&collection_id)
        .join(&tenant_id);

    let tenant_id_for_task = tenant_id.clone();

    let (tree, has_more) = run_blocking(move || {
        git::GitFiles::list_files(
            &repo_path,
            &tenant_id_for_task,
            path_prefix.as_deref(),
            maximum_depth,
            include_hidden_files,
            file_name_starts_with.as_deref(),
            date_filter,
            order_options,
            page,
            per_page,
        )
    })
    .await?;

    tracing::debug!(tenant_id = %tenant_id, page = page, returned = tree.len(), has_more = has_more, "list files tree response ready");

    Ok(Json(json!({
        "page": page,
        "per_page": per_page,
        "has_more": has_more,
        "files": tree,
    })))
}

/// GET /:collection_id/:tenant_id/count/files
/// Returns file and directory count statistics for the repository.
///
/// `prefix_path`, `maximum_depth` and `include_hidden_files` scope the
/// count exactly like the listing endpoint (sub-directory root, depth
/// bound, hidden filter). `restrict_file_extensions` — a JSON-array string,
/// same wire spelling as the `seek_*` prefix lists — narrows the file count
/// to files carrying one of the given extensions, compared
/// case-insensitively; directories are counted regardless.
pub async fn count_files(
    State(state): State<AppState>,
    Path((collection_id, tenant_id)): Path<(String, String)>,
    Query(query): Query<CountFilesQuery>,
) -> Result<impl IntoResponse, AppError> {
    let collection_id = validate::collection_id(&collection_id)?.to_string();
    let tenant_id = validate::tenant_id(&tenant_id)?.to_string();

    // An empty sanitised prefix ("/" or "") means "repo root", which is the
    // same as no prefix at all — normalise it to None here so the git layer
    // only ever sees a meaningful prefix.
    let path_prefix: Option<String> = query
        .prefix_path
        .as_deref()
        .map(validate::folder_path)
        .transpose()?
        .filter(|p| !p.is_empty())
        .map(|p| p.to_string());

    // maximum_depth=0 would mean "count nothing", which is more likely a
    // caller bug than an intent — reject it explicitly.
    let maximum_depth: Option<usize> = match query.maximum_depth {
        Some(0) => {
            return Err(AppError::InvalidOperation {
                reason: "maximum_depth must be at least 1".to_string(),
            })
        }
        Some(d) => Some(d as usize),
        None => None,
    };

    let include_hidden_files = query.include_hidden_files.unwrap_or(false);

    let restrict_file_extensions: Option<Vec<String>> = query
        .restrict_file_extensions
        .as_deref()
        .map(parse_restrict_file_extensions)
        .transpose()?;

    tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, path_prefix = ?path_prefix, maximum_depth = ?maximum_depth, include_hidden_files = include_hidden_files, restrict_file_extensions = ?restrict_file_extensions, "handling count files request");

    let repo_path = state
        .config
        .server
        .repos_path
        .join(&collection_id)
        .join(&tenant_id);

    let tenant_id_for_task = tenant_id.clone();

    let counts = run_blocking(move || {
        git::GitFiles::count_files(
            &repo_path,
            &tenant_id_for_task,
            path_prefix.as_deref(),
            maximum_depth,
            include_hidden_files,
            restrict_file_extensions.as_deref(),
        )
    })
    .await?;

    tracing::debug!(tenant_id = %tenant_id, files = counts.files, directories = counts.directories, "count files response ready");

    Ok(Json(json!({
        "files": counts.files,
        "directories": counts.directories,
    })))
}

/// Decodes and validates the `restrict_file_extensions` query parameter
/// from its JSON-array-string spelling. Entries are normalised by trimming
/// leading dots (`".md"` and `"md"` name the same extension); a non-array
/// value, an empty array, or an entry left empty after trimming are all
/// caller bugs and rejected with a `400`.
fn parse_restrict_file_extensions(raw: &str) -> Result<Vec<String>, AppError> {
    let extensions: Vec<String> =
        serde_json::from_str(raw).map_err(|_err| AppError::InvalidOperation {
            reason:
                "restrict_file_extensions must be a JSON array of strings, e.g. [\"md\", \"mdx\"]"
                    .to_string(),
        })?;

    if extensions.is_empty() {
        return Err(AppError::InvalidOperation {
            reason: "restrict_file_extensions must contain at least one extension".to_string(),
        });
    }

    let normalized: Vec<String> = extensions
        .iter()
        .map(|extension| extension.trim_start_matches('.').to_string())
        .collect();

    if normalized.iter().any(|extension| extension.is_empty()) {
        return Err(AppError::InvalidOperation {
            reason: "restrict_file_extensions extensions must not be empty".to_string(),
        });
    }

    Ok(normalized)
}

/// GET /:collection_id/:tenant_id/files/*path
/// Returns the file content, path, and its position in its parent directory's
/// file order index as JSON (`-1` when the index does not name it, or the
/// directory has no index).
///
/// Optional `seek_*` query parameters (`seek_from_line_starts_with`,
/// `seek_to_line_starts_with`, `seek_lines_maximum`) narrow `content` to a
/// line window — see `seek.rs` for the exact semantics and accepted
/// formats. The seek runs inside the git read so it can scan the blob as a
/// line stream instead of decoding it whole.
pub async fn read_file(
    State(state): State<AppState>,
    Path((collection_id, tenant_id, file_path)): Path<(String, String, String)>,
    Query(seek): Query<SeekOptions>,
) -> Result<impl IntoResponse, AppError> {
    let collection_id = validate::collection_id(&collection_id)?.to_string();
    let tenant_id = validate::tenant_id(&tenant_id)?.to_string();
    let file_path = validate::file_path(&file_path)?.to_string();

    let seek = seek.parse()?;

    tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, path = %file_path, seek = ?seek, "handling read file request");

    let repo_path = state
        .config
        .server
        .repos_path
        .join(&collection_id)
        .join(&tenant_id);

    let file_path_for_task = file_path.clone();
    let tenant_id_for_task = tenant_id.clone();

    let file = run_blocking(move || {
        git::GitFiles::read_file(&repo_path, &tenant_id_for_task, &file_path_for_task, &seek)
    })
    .await?;

    Ok(Json(json!({
        "path": file_path,
        "content": file.content,
        "position": file.position,
    })))
}

/// POST /:collection_id/:tenant_id/batch/files/read
/// Reads several files in one request. The response array is index-aligned
/// with the request's `files` array: each slot is either the same
/// `{ path, content }` object the single read route returns, or `null`
/// when that path does not exist (or is a folder). Each entry is a bare
/// path string or a `{ path, seek? }` object; an optional request-level
/// `seek` object applies the same line window to every file, and an
/// entry-level `seek` replaces it for that file.
///
/// The whole request is rejected upfront (400) when a path is invalid,
/// paths are duplicated, or more than `limits.batch_read_maximum_files`
/// paths are asked for — a safety cap against unbounded response sizes.
/// A file that exists but cannot be represented (invalid UTF-8) fails the
/// whole batch with a 422, so `null` strictly means "not found".
pub async fn batch_read_files(
    State(state): State<AppState>,
    Path((collection_id, tenant_id)): Path<(String, String)>,
    Json(body): Json<BatchReadFilesRequest>,
) -> Result<impl IntoResponse, AppError> {
    let collection_id = validate::collection_id(&collection_id)?.to_string();
    let tenant_id = validate::tenant_id(&tenant_id)?.to_string();

    if body.files.is_empty() {
        return Err(AppError::InvalidOperation {
            reason: "files must contain at least one path".to_string(),
        });
    }

    let maximum_files = state.config.limits.batch_read_maximum_files;

    if body.files.len() > maximum_files {
        return Err(AppError::InvalidOperation {
            reason: format!(
                "files must not contain more than {} paths ({} requested)",
                maximum_files,
                body.files.len()
            ),
        });
    }

    let global_seek = body.seek.unwrap_or_default().parse()?;

    // Sanitise every path with the same rules as the single read route,
    // *before* the uniqueness check so that two spellings of the same file
    // (e.g. `a.md` and `/a.md`) are caught as duplicates. Each entry's
    // effective seek is resolved here too: its own window when it carries
    // one, the request-level window otherwise.
    let mut seen_paths = HashSet::new();
    let mut file_reads: Vec<(String, SeekFilter)> = Vec::with_capacity(body.files.len());

    for (index, entry) in body.files.iter().enumerate() {
        let (raw_path, entry_seek) = entry.parts();

        let file_path = validate::file_path(raw_path)?.to_string();

        if !seen_paths.insert(file_path.clone()) {
            return Err(AppError::InvalidOperation {
                reason: format!("files must be unique: '{}' is requested twice", file_path),
            });
        }

        let seek = match entry_seek {
            None => global_seek.clone(),

            // Prefix validation errors with the entry's index so the caller
            // knows which per-file seek is malformed (the request-level one
            // reports without a prefix).
            Some(entry_seek) => entry_seek.parse().map_err(|err| match err {
                AppError::InvalidOperation { reason } => AppError::InvalidOperation {
                    reason: format!("files[{}]: {}", index, reason),
                },
                other => other,
            })?,
        };

        file_reads.push((file_path, seek));
    }

    tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, count = file_reads.len(), seek = ?global_seek, "handling batch read files request");

    let repo_path = state
        .config
        .server
        .repos_path
        .join(&collection_id)
        .join(&tenant_id);

    let file_reads_for_task = file_reads.clone();

    let contents = run_blocking(move || {
        git::GitFiles::batch_read_files(&repo_path, &tenant_id, &file_reads_for_task)
    })
    .await?;

    let files: Vec<_> = file_reads
        .iter()
        .zip(contents)
        .map(|((path, _seek), content)| {
            content.map(|content| json!({ "path": path, "content": content }))
        })
        .collect();

    Ok(Json(json!({ "files": files })))
}

/// HEAD /:collection_id/:tenant_id/files/*path
/// Returns 200 with no body when the file exists in HEAD, 404 otherwise.
/// Cheaper than GET as the blob content is never loaded.
///
/// With `?check_prefix_path=true` a folder at that path counts as existing
/// too — the answer becomes "is there anything here", which is what a caller
/// about to recurse a delete or a move needs to know. Both kinds are read
/// from HEAD's tree entry, so the check stays a single tree lookup either way.
pub async fn file_exists(
    State(state): State<AppState>,
    Path((collection_id, tenant_id, file_path)): Path<(String, String, String)>,
    Query(query): Query<FileExistsQuery>,
) -> Result<impl IntoResponse, AppError> {
    let collection_id = validate::collection_id(&collection_id)?.to_string();
    let tenant_id = validate::tenant_id(&tenant_id)?.to_string();

    let check_prefix_path = query.check_prefix_path.unwrap_or(false);

    // Folders are naturally spelled with a trailing slash, so tolerate one
    // once folders are in scope at all.
    let file_path = if check_prefix_path {
        validate::file_or_folder_path(&file_path)?
    } else {
        validate::file_path(&file_path)?
    }
    .to_string();

    tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, path = %file_path, check_prefix_path = check_prefix_path, "handling file existence request");

    let repo_path = state
        .config
        .server
        .repos_path
        .join(&collection_id)
        .join(&tenant_id);

    let file_path_for_task = file_path.clone();

    let kind =
        run_blocking(move || git::GitFiles::path_kind(&repo_path, &tenant_id, &file_path_for_task))
            .await?;

    match kind {
        git::PathKind::File => Ok(StatusCode::OK),
        git::PathKind::Directory if check_prefix_path => Ok(StatusCode::OK),
        _ => Err(AppError::FileNotFound { path: file_path }),
    }
}

/// PUT /:collection_id/:tenant_id/files/*path
/// Creates or updates a file, commits the change, and fires a hook.
///
/// PUT is idempotent by design: the caller does not need to know whether the
/// file exists. The server decides created-vs-updated from HEAD's tree and
/// reflects that in both the auto-generated commit message and the hook
/// event kind. Idempotency extends to content: re-PUTting a file with the
/// exact content HEAD already holds creates no commit and fires no hook —
/// the response carries HEAD's sha instead. This is also the endpoint that
/// lazily initialises a tenant repository on first use — there is no
/// explicit "create tenant" call.
pub async fn write_file(
    State(state): State<AppState>,
    Path((collection_id, tenant_id, file_path)): Path<(String, String, String)>,
    Json(body): Json<WriteFileRequest>,
) -> Result<impl IntoResponse, AppError> {
    let collection_id = validate::collection_id(&collection_id)?.to_string();
    let tenant_id = validate::tenant_id(&tenant_id)?.to_string();
    let file_path = validate::file_path(&file_path)?.to_string();

    validate::file_extension(
        &file_path,
        state.config.limits.allowed_extensions.as_deref(),
    )?;

    tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, path = %file_path, "handling write file request");

    let repo_path = state
        .config
        .server
        .repos_path
        .join(&collection_id)
        .join(&tenant_id);

    let lock_key = format!("{}/{}", collection_id, tenant_id);
    let lock = state.get_repo_lock(&lock_key);
    let _lock_guard = lock.lock().await;

    let WriteFileRequest {
        author,
        content,
        message,
    } = body;

    let repo_path_for_maintenance = repo_path.clone();

    let (commit_sha, file_change) = run_blocking(move || {
        git::GitFiles::write_file(
            &repo_path,
            &file_path,
            &content,
            message.as_deref(),
            &author.name,
            &author.email,
        )
    })
    .await?;

    // A `None` change means the content already matched HEAD: no commit was
    // created, so there is nothing for downstream systems to sync and no new
    // objects for maintenance to consolidate. The returned sha is HEAD's —
    // the commit whose tree already contains exactly this content.
    let Some(file_change) = file_change else {
        tracing::debug!(tenant_id = %tenant_id, sha = %commit_sha, "content unchanged, no commit created");

        return Ok((StatusCode::OK, Json(json!({ "commit_sha": commit_sha }))));
    };

    tracing::debug!(tenant_id = %tenant_id, sha = %commit_sha, "file write committed, enqueuing hook delivery");

    // Enqueued while the tenant write lock is still held, so per-tenant hook
    // order always matches commit order.
    state.hook_queue.enqueue(
        &lock_key,
        HookJob::new(
            collection_id,
            tenant_id,
            commit_sha.clone(),
            Utc::now(),
            vec![file_change],
        ),
    );

    state
        .maintenance
        .schedule(&lock_key, repo_path_for_maintenance, lock.clone());

    Ok((StatusCode::OK, Json(json!({ "commit_sha": commit_sha }))))
}

/// DELETE /:collection_id/:tenant_id/files/*path
/// Deletes a file, commits the removal, and fires a hook.
///
/// With `allow_prefix_path_recurse: true` in the body the path may also name a
/// folder, in which case every file beneath it is removed in one commit and
/// one `file.deleted` hook fires per file. Without the opt-in a folder path is
/// simply not a file and answers `404`, so this destructive mode is never
/// entered by accident.
pub async fn delete_file(
    State(state): State<AppState>,
    Path((collection_id, tenant_id, file_path)): Path<(String, String, String)>,
    Json(body): Json<DeleteFileRequest>,
) -> Result<impl IntoResponse, AppError> {
    let collection_id = validate::collection_id(&collection_id)?.to_string();
    let tenant_id = validate::tenant_id(&tenant_id)?.to_string();

    let allow_prefix_path_recurse = body.allow_prefix_path_recurse.unwrap_or(false);

    // Folders are naturally spelled with a trailing slash, so tolerate one
    // once folders are in scope at all.
    let file_path = if allow_prefix_path_recurse {
        validate::file_or_folder_path(&file_path)?
    } else {
        validate::file_path(&file_path)?
    }
    .to_string();

    tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, path = %file_path, allow_prefix_path_recurse = allow_prefix_path_recurse, "handling delete file request");

    let repo_path = state
        .config
        .server
        .repos_path
        .join(&collection_id)
        .join(&tenant_id);

    let lock_key = format!("{}/{}", collection_id, tenant_id);
    let lock = state.get_repo_lock(&lock_key);
    let _lock_guard = lock.lock().await;

    let DeleteFileRequest {
        author,
        message,
        allow_prefix_path_recurse: _,
    } = body;

    let repo_path_for_maintenance = repo_path.clone();

    // Which of the two operations to run is decided from HEAD's tree, under
    // the write lock, so the classification cannot go stale before the commit
    // it drives. The lookup is only paid for when the caller opted in — with
    // recursion off the single-file path is unchanged, folder and all.
    let recurse_directory = if allow_prefix_path_recurse {
        let repo_path_for_kind = repo_path.clone();
        let tenant_id_for_kind = tenant_id.clone();
        let file_path_for_kind = file_path.clone();

        let kind = run_blocking(move || {
            git::GitFiles::path_kind(
                &repo_path_for_kind,
                &tenant_id_for_kind,
                &file_path_for_kind,
            )
        })
        .await?;

        kind == git::PathKind::Directory
    } else {
        false
    };

    let tenant_id_for_task = tenant_id.clone();

    let (commit_sha, file_changes) = if recurse_directory {
        run_blocking(move || {
            git::GitFiles::delete_directory(
                &repo_path,
                &tenant_id_for_task,
                &file_path,
                message.as_deref(),
                &author.name,
                &author.email,
            )
        })
        .await?
    } else {
        run_blocking(move || {
            git::GitFiles::delete_file(
                &repo_path,
                &tenant_id_for_task,
                &file_path,
                message.as_deref(),
                &author.name,
                &author.email,
            )
        })
        .await?
    };

    // An empty change list means no commit was created (only reachable on the
    // recursive path, for a folder holding nothing this API represents), so
    // there is nothing to sync and no new objects to consolidate.
    if file_changes.is_empty() {
        tracing::debug!(tenant_id = %tenant_id, sha = %commit_sha, "nothing to delete, no commit created");

        return Ok((StatusCode::OK, Json(json!({ "commit_sha": commit_sha }))));
    }

    tracing::debug!(tenant_id = %tenant_id, sha = %commit_sha, file_count = file_changes.len(), "file deletion committed, enqueuing hook delivery");

    // Enqueued while the tenant write lock is still held, so per-tenant hook
    // order always matches commit order.
    state.hook_queue.enqueue(
        &lock_key,
        HookJob::new(
            collection_id,
            tenant_id,
            commit_sha.clone(),
            Utc::now(),
            file_changes,
        ),
    );

    state
        .maintenance
        .schedule(&lock_key, repo_path_for_maintenance, lock.clone());

    Ok((StatusCode::OK, Json(json!({ "commit_sha": commit_sha }))))
}

/// POST /:collection_id/:tenant_id/files/*path/{move,reorder}
/// The two POST operations on a file path, dispatched on the URL suffix.
///
/// Axum cannot match a fixed suffix after a wildcard segment, so both are
/// registered on POST `/*path` and the suffix is enforced here. The body is
/// therefore taken as raw JSON and deserialised once the suffix has said which
/// operation it belongs to — the suffix decides, never the body's shape, so a
/// mistyped field can never turn one operation into the other.
pub async fn post_file(
    State(state): State<AppState>,
    Path((collection_id, tenant_id, raw_path)): Path<(String, String, String)>,
    Json(body): Json<Value>,
) -> Result<(StatusCode, Json<Value>), AppError> {
    if let Some(from_path_raw) = raw_path.strip_suffix("/move") {
        return move_file(
            state,
            collection_id,
            tenant_id,
            from_path_raw,
            parse_body(body)?,
        )
        .await;
    }

    if let Some(file_path_raw) = raw_path.strip_suffix("/reorder") {
        return reorder_file(
            state,
            collection_id,
            tenant_id,
            file_path_raw,
            parse_body(body)?,
        )
        .await;
    }

    Err(AppError::InvalidPath {
        reason: "POST on a file path must end with /move or /reorder".to_string(),
    })
}

/// Deserialises an already-parsed JSON body into the request type the URL
/// suffix selected, reporting a malformed one as a `400` in this API's own
/// error shape rather than as an extractor rejection.
fn parse_body<T: DeserializeOwned>(body: Value) -> Result<T, AppError> {
    serde_json::from_value(body).map_err(|err| AppError::InvalidOperation {
        reason: format!("invalid request body: {}", err),
    })
}

/// POST /:collection_id/:tenant_id/files/*path/move
/// Moves/renames a file to a new path in a single atomic commit, fires a
/// single hook with both the old and new paths so the receiver can
/// correlate the rename without losing attached metadata.
///
/// With `allow_prefix_path_recurse: true` in the body the source may also name
/// a folder, in which case the whole folder is relocated in one commit and one
/// `file.moved` hook fires per file — every file keeping its own leaf name, so
/// downstream entity identity survives. Without the opt-in a folder source is
/// simply not a file and answers `404`.
async fn move_file(
    state: AppState,
    collection_id: String,
    tenant_id: String,
    from_path_raw: &str,
    body: MoveFileRequest,
) -> Result<(StatusCode, Json<Value>), AppError> {
    let collection_id = validate::collection_id(&collection_id)?.to_string();
    let tenant_id = validate::tenant_id(&tenant_id)?.to_string();

    let allow_prefix_path_recurse = body.allow_prefix_path_recurse.unwrap_or(false);

    // Folders are naturally spelled with a trailing slash, so tolerate one on
    // both sides once folders are in scope at all.
    let (from_path, to_path) = if allow_prefix_path_recurse {
        (
            validate::file_or_folder_path(from_path_raw)?.to_string(),
            validate::file_or_folder_path(&body.destination)?.to_string(),
        )
    } else {
        (
            validate::file_path(from_path_raw)?.to_string(),
            validate::file_path(&body.destination)?.to_string(),
        )
    };

    // Only the destination is checked against the whitelist: files written
    // before the whitelist was configured must remain movable. With recursion
    // enabled the check is deferred until the source kind is known — a folder
    // destination carries no extension of its own, and the files inside keep
    // their leaf names, so there is nothing there for the whitelist to guard.
    if !allow_prefix_path_recurse {
        validate::file_extension(&to_path, state.config.limits.allowed_extensions.as_deref())?;
    }

    tracing::debug!(
        collection_id = %collection_id,
        tenant_id = %tenant_id,
        from_path = %from_path,
        to_path = %to_path,
        allow_prefix_path_recurse = allow_prefix_path_recurse,
        "handling move file request"
    );

    let repo_path = state
        .config
        .server
        .repos_path
        .join(&collection_id)
        .join(&tenant_id);

    let lock_key = format!("{}/{}", collection_id, tenant_id);
    let lock = state.get_repo_lock(&lock_key);
    let _lock_guard = lock.lock().await;

    let MoveFileRequest {
        author,
        destination: _,
        message,
        allow_prefix_path_recurse: _,
    } = body;

    let repo_path_for_maintenance = repo_path.clone();

    // Which of the two operations to run is decided from HEAD's tree, under
    // the write lock, so the classification cannot go stale before the commit
    // it drives. The lookup is only paid for when the caller opted in.
    let recurse_directory = if allow_prefix_path_recurse {
        let repo_path_for_kind = repo_path.clone();
        let tenant_id_for_kind = tenant_id.clone();
        let from_path_for_kind = from_path.clone();

        let kind = run_blocking(move || {
            git::GitFiles::path_kind(
                &repo_path_for_kind,
                &tenant_id_for_kind,
                &from_path_for_kind,
            )
        })
        .await?;

        kind == git::PathKind::Directory
    } else {
        false
    };

    // The source turned out to be a file after all (or nothing at all), so
    // the destination is a file path and the whitelist applies as usual.
    if allow_prefix_path_recurse && !recurse_directory {
        validate::file_extension(&to_path, state.config.limits.allowed_extensions.as_deref())?;
    }

    let tenant_id_for_task = tenant_id.clone();

    let (commit_sha, file_changes) = if recurse_directory {
        run_blocking(move || {
            git::GitFiles::move_directory(
                &repo_path,
                &tenant_id_for_task,
                &from_path,
                &to_path,
                message.as_deref(),
                &author.name,
                &author.email,
            )
        })
        .await?
    } else {
        run_blocking(move || {
            git::GitFiles::move_file(
                &repo_path,
                &tenant_id_for_task,
                &from_path,
                &to_path,
                message.as_deref(),
                &author.name,
                &author.email,
            )
        })
        .await?
    };

    // An empty change list means no commit was created (only reachable on the
    // recursive path, for a folder holding nothing this API represents), so
    // there is nothing to sync and no new objects to consolidate.
    if file_changes.is_empty() {
        tracing::debug!(tenant_id = %tenant_id, sha = %commit_sha, "nothing to move, no commit created");

        return Ok((StatusCode::OK, Json(json!({ "commit_sha": commit_sha }))));
    }

    tracing::debug!(tenant_id = %tenant_id, sha = %commit_sha, file_count = file_changes.len(), "file move committed, enqueuing hook delivery");

    // Enqueued while the tenant write lock is still held, so per-tenant hook
    // order always matches commit order.
    state.hook_queue.enqueue(
        &lock_key,
        HookJob::new(
            collection_id,
            tenant_id,
            commit_sha.clone(),
            Utc::now(),
            file_changes,
        ),
    );

    state
        .maintenance
        .schedule(&lock_key, repo_path_for_maintenance, lock.clone());

    Ok((StatusCode::OK, Json(json!({ "commit_sha": commit_sha }))))
}

/// POST /:collection_id/:tenant_id/files/*path/reorder
/// Gives one file a numerical position inside its parent directory's file order
/// index, shifting the entries at and after that position down by one, and
/// fires one `order.updated` hook carrying the resulting order.
///
/// The index is materialised over the whole directory first: every sibling it
/// does not name yet is folded in at the rank a listing renders it with, so the
/// position the caller sent counts against the rows they were looking at rather
/// than against however few entries happen to be pinned. `implicit_order_default_index`
/// says where those siblings are folded in and carries the listing parameter's
/// meaning exactly — unset leaves them behind everything listed, `0` lifts them
/// above it — so a caller passes back whatever it rendered with. A parent with no
/// index yet gets one covering the directory; the caller explicitly asked for a
/// position, exactly as they would through `PUT /order`. A position past the end
/// is clamped to the tail, and asking for the arrangement the index already holds
/// is a no-op: no commit, no hook, HEAD's sha.
///
/// Hidden (dot-prefixed) siblings are left out of the materialised index unless
/// `implicit_allow_hidden_files: true` — an index the server generates should not
/// quietly pin a repository's metadata — though one the index already names is
/// kept, since positioning an unrelated file is no occasion to unpin it. The flag
/// is *required* when the positioned entry is itself hidden (`400` otherwise):
/// pinning a dot-file has to be asked for.
///
/// `position: -1` is the inverse: it drops the entry from the index, leaving it
/// implicitly ordered again (the file itself is untouched, and nothing is
/// materialised — unpinning one entry is no reason to pin every other one, so an
/// already-unlisted entry stays a no-op). That is the value the read route
/// reports for an unlisted file, so what a caller reads back is what it can send.
/// When it empties the index, the index is removed rather than stored empty and
/// the event is `order.deleted`.
///
/// With `allow_prefix_path: true` in the body the path may also name a folder,
/// positioning the folder itself among its siblings (an index interleaves files
/// and directories freely). Without the opt-in a folder path is simply not a
/// file and answers `404`. Nothing recurses either way: a folder's position is
/// one entry in one index, and its contents are untouched.
///
/// It commits through the same machinery as the order routes, so the change
/// arrives as an `order.updated` event on the parent directory rather than as a
/// `file.*` one — the entry itself is untouched.
async fn reorder_file(
    state: AppState,
    collection_id: String,
    tenant_id: String,
    entry_path_raw: &str,
    body: ReorderFileRequest,
) -> Result<(StatusCode, Json<Value>), AppError> {
    let collection_id = validate::collection_id(&collection_id)?.to_string();
    let tenant_id = validate::tenant_id(&tenant_id)?.to_string();

    let allow_prefix_path = body.allow_prefix_path.unwrap_or(false);

    // Folders are naturally spelled with a trailing slash, so tolerate one
    // once folders are in scope at all.
    let entry_path = if allow_prefix_path {
        validate::file_or_folder_path(entry_path_raw)?
    } else {
        validate::file_path(entry_path_raw)?
    }
    .to_string();

    // Positions are indexes into a list, so `-1` is the only negative value
    // that means anything: it is what the read route reports for an unlisted
    // entry, and sending it back drops the entry from the index. Anything
    // further below zero is a caller bug.
    let position = match body.position {
        position if position >= 0 => git::OrderPosition::At(position as usize),

        order::UNLISTED_POSITION => git::OrderPosition::Unlisted,

        position => {
            return Err(AppError::InvalidOperation {
                reason: format!(
                    "position must be zero or greater, or {} to drop the entry from the index: {}",
                    order::UNLISTED_POSITION,
                    position
                ),
            })
        }
    };

    let implicit_allow_hidden_files = body.implicit_allow_hidden_files.unwrap_or(false);

    // Pinning a dot-file has to be asked for, so the flag that keeps hidden
    // siblings out of the generated index is *required* when the positioned
    // entry is itself hidden — one answer per request rather than a second flag
    // that could contradict this one. Judged on the sanitised leaf name alone,
    // so it costs no repository access. Only `At` pins anything: `-1` unpins,
    // which is the guardrail's own direction and needs no opt-in.
    if matches!(position, git::OrderPosition::At(_))
        && !implicit_allow_hidden_files
        && order::is_hidden(order::split_parent(&entry_path).1)
    {
        return Err(AppError::InvalidOperation {
            reason: format!(
                "entry is a hidden file; set implicit_allow_hidden_files to give it a position: {}",
                entry_path
            ),
        });
    }

    tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, path = %entry_path, position = ?position, implicit_order_default_index = ?body.implicit_order_default_index, implicit_allow_hidden_files = implicit_allow_hidden_files, allow_prefix_path = allow_prefix_path, "handling reorder file request");

    let repo_path = state
        .config
        .server
        .repos_path
        .join(&collection_id)
        .join(&tenant_id);

    let lock_key = format!("{}/{}", collection_id, tenant_id);
    let lock = state.get_repo_lock(&lock_key);
    let _lock_guard = lock.lock().await;

    let ReorderFileRequest {
        author,
        position: _,
        implicit_order_default_index,
        implicit_allow_hidden_files: _,
        message,
        allow_prefix_path: _,
    } = body;

    let repo_path_for_maintenance = repo_path.clone();
    let tenant_id_for_task = tenant_id.clone();

    let (commit_sha, change) = run_blocking(move || {
        git::GitOrder::reorder_entry(
            &repo_path,
            &tenant_id_for_task,
            &entry_path,
            position,
            implicit_order_default_index,
            implicit_allow_hidden_files,
            allow_prefix_path,
            message.as_deref(),
            &author.name,
            &author.email,
        )
    })
    .await?;

    // A `None` change means the index already gave the file that position: no
    // commit was created, so there is nothing to sync and no new objects for
    // maintenance to consolidate.
    let Some(change) = change else {
        tracing::debug!(tenant_id = %tenant_id, sha = %commit_sha, "order unchanged, no commit created");

        return Ok((StatusCode::OK, Json(json!({ "commit_sha": commit_sha }))));
    };

    tracing::debug!(tenant_id = %tenant_id, sha = %commit_sha, "order reorder committed, enqueuing hook delivery");

    // Enqueued while the tenant write lock is still held, so per-tenant hook
    // order always matches commit order. The change lands on the index's own
    // path, which is what `HookJob::new` classifies into an order event.
    state.hook_queue.enqueue(
        &lock_key,
        HookJob::new(
            collection_id,
            tenant_id,
            commit_sha.clone(),
            Utc::now(),
            vec![change],
        ),
    );

    state
        .maintenance
        .schedule(&lock_key, repo_path_for_maintenance, lock.clone());

    Ok((StatusCode::OK, Json(json!({ "commit_sha": commit_sha }))))
}