firestore 0.59.0

Library provides a simple API for Google Firestore and own Serde serializer based on efficient gRPC API
Documentation
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
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
//! Declarative index, single-field override and TTL model for one collection group.
//!
//! Nothing here performs I/O. [`FirestoreIndexParams`] is what a fluent
//! `db.fluent().indexes()...` chain assembles, and what `FirestoreDb`'s index management passes
//! on to Firestore.

use crate::errors::FirestoreError;
use crate::{FirestoreCollectionId, FirestoreQueryDirection, FirestoreResult};
use rsb_derive::Builder;
use std::collections::HashSet;
use std::fmt::{self, Display, Formatter};
use std::time::Duration;

/// The reserved field path Firestore appends to every composite index at creation time.
pub(crate) const IMPLIED_NAME_FIELD: &str = "__name__";

/// Whether an index serves queries against one collection or a collection-group query across
/// every collection with the same ID anywhere under the database.
///
/// This is the same distinction [`.all_descendants()`](crate::select_builder::FirestoreSelectDocBuilder::all_descendants)
/// makes for a query: a `CollectionGroup`-scoped index is exactly what such a query needs.
#[derive(Debug, Eq, PartialEq, Clone, Copy, Hash, Default)]
pub enum FirestoreIndexQueryScope {
    /// Serves queries against a single collection at a known path.
    #[default]
    Collection,
    /// Serves collection-group queries: every collection with this ID, anywhere under the
    /// database.
    AllDescendants,
}

/// A flat vector index's configuration, for nearest-neighbor search.
#[derive(Debug, PartialEq, Eq, Hash, Clone, Builder)]
pub struct FirestoreVectorIndexConfig {
    /// The dimension every indexed vector in this field must have.
    pub dimension: u32,
}

/// How a single field participates in an index.
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub enum FirestoreIndexFieldMode {
    /// Sortable and comparable in the given direction.
    Order(FirestoreQueryDirection),
    /// Queryable with array-containment operators.
    ArrayContains,
    /// A flat vector index of a fixed dimension, for nearest-neighbor search.
    Vector(FirestoreVectorIndexConfig),
}

/// One field of a composite index: its path and how it participates.
#[derive(Debug, PartialEq, Clone)]
pub struct FirestoreIndexField {
    /// The field's path within a document.
    pub field_path: String,
    /// How the field is indexed.
    pub mode: FirestoreIndexFieldMode,
}

impl FirestoreIndexField {
    pub(crate) fn new(field_path: String, mode: FirestoreIndexFieldMode) -> Self {
        Self { field_path, mode }
    }
}

/// A declared composite index: an ordered list of fields plus the scope it serves.
///
/// Build one with [`FirestoreCompositeIndexBuilder::index`](crate::index_builder::FirestoreCompositeIndexBuilder::index);
/// it defaults to [`FirestoreIndexQueryScope::Collection`] until [`all_descendants`](Self::all_descendants)
/// is chained onto it.
#[derive(Debug, PartialEq, Clone)]
pub struct FirestoreCompositeIndex {
    /// The indexed fields, in the order Firestore evaluates them.
    pub fields: Vec<FirestoreIndexField>,
    /// Whether this index serves a single collection or every collection with the same ID.
    pub query_scope: FirestoreIndexQueryScope,
}

impl FirestoreCompositeIndex {
    pub(crate) fn new(fields: Vec<FirestoreIndexField>) -> Self {
        Self {
            fields,
            query_scope: FirestoreIndexQueryScope::Collection,
        }
    }

    /// Scopes this index to a collection-group query instead of a single collection.
    #[inline]
    pub fn all_descendants(mut self) -> Self {
        self.query_scope = FirestoreIndexQueryScope::AllDescendants;
        self
    }
}

/// One single-field index a [`FirestoreFieldOverride`] declares explicitly.
///
/// Build one from [`FirestoreFieldOverrideBuilder`](crate::index_builder::FirestoreFieldOverrideBuilder)'s
/// `.ascending()`, `.descending()` or `.array_contains()`; it defaults to
/// [`FirestoreIndexQueryScope::Collection`] until [`all_descendants`](Self::all_descendants) is
/// chained onto it.
#[derive(Debug, PartialEq, Clone)]
pub struct FirestoreFieldOverrideIndex {
    /// Whether this single-field index serves a single collection or every collection with the
    /// same ID.
    pub query_scope: FirestoreIndexQueryScope,
    /// How the field is indexed.
    pub mode: FirestoreIndexFieldMode,
}

impl FirestoreFieldOverrideIndex {
    pub(crate) fn new(mode: FirestoreIndexFieldMode) -> Self {
        Self {
            query_scope: FirestoreIndexQueryScope::Collection,
            mode,
        }
    }

    /// Scopes this single-field index to a collection-group query instead of a single
    /// collection.
    #[inline]
    pub fn all_descendants(mut self) -> Self {
        self.query_scope = FirestoreIndexQueryScope::AllDescendants;
        self
    }
}

/// The Firestore special field path (`*`) that targets every field in a collection group, in
/// place of one named field. Reachable only through
/// [`all_fields()`](crate::index_builder::FirestoreFieldOverrideBuilder::all_fields), never as a
/// literal string: see [`FirestoreFieldOverrideTarget`].
pub(crate) const ALL_FIELDS_PATH: &str = "*";

/// A field path in the one spelling Firestore's grammar allows for it, so two spellings of the
/// same field compare and hash equal: `` `x` `` and `x`, or `` a.`b` `` and `` `a`.b ``.
///
/// A segment is written bare when it is a simple identifier (`[A-Za-z_][A-Za-z0-9_]*`), and in
/// backticks otherwise, with `` \` `` and `\\` escaping a backtick and a backslash inside them.
/// The all-fields wildcard `*` is kept as it is. A path that does not parse, such as one with an
/// unclosed backtick, is kept exactly as written, so it only ever equals the same text.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct CanonicalFieldPath(String);

impl CanonicalFieldPath {
    /// The field path of a listed field resource,
    /// `projects/{p}/databases/{d}/collectionGroups/{group}/fields/{path}`.
    ///
    /// Anchored on the `/collectionGroups/{group}/fields/` markers rather than split on the last
    /// `/`, because a quoted segment such as `` `a/b` `` can itself contain `/`, and a database ID
    /// can contain the word `fields`.
    ///
    /// # Errors
    /// [`FirestoreError::InvalidParametersError`] naming `name` when it is not a field resource
    /// name of that shape.
    pub(crate) fn from_field_resource_name(name: &str) -> FirestoreResult<Self> {
        const COLLECTION_GROUPS_MARKER: &str = "/collectionGroups/";
        const FIELDS_MARKER: &str = "fields/";

        name.find(COLLECTION_GROUPS_MARKER)
            .and_then(|groups_at| {
                let after_groups = &name[groups_at + COLLECTION_GROUPS_MARKER.len()..];
                let group_end = after_groups.find('/')?;
                after_groups[group_end + 1..].strip_prefix(FIELDS_MARKER)
            })
            .map(Self::from)
            .ok_or_else(|| {
                FirestoreError::invalid_parameters(
                    "name",
                    format!("not a field resource name: {name}"),
                )
            })
    }

    pub(crate) fn as_str(&self) -> &str {
        &self.0
    }

    /// The unescaped name of every segment of `path`, or `None` when `path` does not follow the
    /// field path grammar.
    fn segments(path: &str) -> Option<Vec<String>> {
        let mut segments = Vec::new();
        let mut chars = path.chars();
        loop {
            let mut segment = String::new();
            let mut rest = chars.clone();
            let ended = if rest.next() == Some('`') {
                chars = rest;
                loop {
                    match chars.next()? {
                        '\\' => segment.push(chars.next()?),
                        '`' => break,
                        c => segment.push(c),
                    }
                }
                match chars.next() {
                    None => true,
                    Some('.') => false,
                    Some(_) => return None,
                }
            } else {
                loop {
                    match chars.next() {
                        None => break true,
                        Some('.') => break false,
                        Some('`') => return None,
                        Some(c) => segment.push(c),
                    }
                }
            };
            if segment.is_empty() {
                return None;
            }
            segments.push(segment);
            if ended {
                return Some(segments);
            }
        }
    }

    fn is_simple_identifier(segment: &str) -> bool {
        let mut chars = segment.chars();
        chars
            .next()
            .is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
            && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
    }
}

impl From<&str> for CanonicalFieldPath {
    fn from(path: &str) -> Self {
        if path == ALL_FIELDS_PATH {
            return Self(path.to_string());
        }
        let Some(segments) = Self::segments(path) else {
            return Self(path.to_string());
        };
        let mut canonical = String::with_capacity(path.len());
        for (position, segment) in segments.iter().enumerate() {
            if position > 0 {
                canonical.push('.');
            }
            if Self::is_simple_identifier(segment) {
                canonical.push_str(segment);
            } else {
                canonical.push('`');
                for c in segment.chars() {
                    if c == '`' || c == '\\' {
                        canonical.push('\\');
                    }
                    canonical.push(c);
                }
                canonical.push('`');
            }
        }
        Self(canonical)
    }
}

impl Display for CanonicalFieldPath {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

/// What a [`FirestoreFieldOverride`] applies to: one named field, or every field in the owned
/// collection group.
///
/// A bare `field_path: String` would let `"*"` arrive through
/// [`field()`](crate::index_builder::FirestoreFieldOverrideBuilder::field) indistinguishably from
/// [`all_fields()`](crate::index_builder::FirestoreFieldOverrideBuilder::all_fields), so validation
/// could never tell "the caller meant the wildcard" from "the caller has a field literally named
/// `*`". Splitting the two into their own variants makes `field("*")` a value validation can
/// reject outright, pointing the caller at `all_fields()`.
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub enum FirestoreFieldOverrideTarget {
    /// One field's path within a document.
    Field(String),
    /// Every field in the owned collection group that has no more specific, named override.
    AllFields,
}

impl FirestoreFieldOverrideTarget {
    /// The resource path segment this target corresponds to: the field path itself, or `*` for
    /// [`AllFields`](Self::AllFields).
    pub(crate) fn as_str(&self) -> &str {
        match self {
            FirestoreFieldOverrideTarget::Field(path) => path.as_str(),
            FirestoreFieldOverrideTarget::AllFields => ALL_FIELDS_PATH,
        }
    }
}

/// A single-field index override: the automatic indexes Firestore would otherwise build for
/// `target`, replaced by exactly the indexes listed here.
///
/// **This replaces the field's whole automatic index set, it does not add to it.** Declaring
/// only `array_contains()` on a field that is also compared with `==` and ordered removes the
/// automatic equality and ordering support for that field, because Firestore does not merge an
/// override with its defaults - neither does `firestore.indexes.json`. An empty index list
/// (equivalently, [`exempt()`](crate::index_builder::FirestoreFieldOverrideFieldBuilder::exempt))
/// excludes the field from single-field indexing entirely.
#[derive(Debug, PartialEq, Clone)]
pub struct FirestoreFieldOverride {
    /// What this override applies to.
    pub target: FirestoreFieldOverrideTarget,
    /// The exact set of single-field indexes to maintain for this target. Empty means exempt.
    pub indexes: Vec<FirestoreFieldOverrideIndex>,
}

/// The lifecycle state Firestore reports for a listed composite index.
#[derive(Debug, Eq, PartialEq, Clone, Copy, Hash)]
pub enum FirestoreIndexState {
    /// There is an active long-running operation building the index.
    Creating,
    /// The index is fully built and serving queries.
    Ready,
    /// The most recent build failed and left no active operation. A declared index matched to
    /// one in this state is reported only; `.sync()` never deletes or recreates it. An
    /// *undeclared* index in this state is pruned like any other undeclared index when `prune`
    /// is set - Firestore does not exempt it.
    NeedsRepair,
}

/// The lifecycle state Firestore reports for a listed field's TTL configuration.
#[derive(Debug, Eq, PartialEq, Clone, Copy, Hash)]
pub enum FirestoreFieldTtlState {
    /// There is an active long-running operation applying TTL to existing documents.
    Creating,
    /// TTL is active for all documents that carry the field.
    Active,
    /// The long-running operation that last tried to enable TTL failed.
    NeedsRepair,
}

/// One composite index Firestore has listed for the owned collection group.
#[derive(Debug, PartialEq, Clone)]
pub struct FirestoreListedCompositeIndex {
    /// The resource name Firestore assigned this index, for logging or a delete call.
    pub name: String,
    /// The index's current lifecycle state.
    pub state: FirestoreIndexState,
    /// The index in the same shape a declaration would take.
    pub index: FirestoreCompositeIndex,
}

/// An explicit, non-inherited single-field index override, as listed for one field resource.
#[derive(Debug, PartialEq, Clone)]
pub struct FirestoreExplicitFieldOverride {
    /// The field's explicit single-field index set. Empty is an explicit exemption, the same as
    /// [`exempt()`](crate::index_builder::FirestoreFieldOverrideFieldBuilder::exempt).
    pub indexes: Vec<FirestoreFieldOverrideIndex>,
    /// Whether Firestore is already reverting this override to the ancestor's configuration (an
    /// in-progress `reverting` long-running change). The planner treats a field with this set as
    /// already handled and never plans reverting it a second time.
    pub reverting: bool,
}

/// A field resource's single-field index configuration, as read from a listed [`ProtoField`]
/// (`gcloud_sdk::google::firestore::admin::v1::Field`).
///
/// Carries its own outcome rather than failing the whole field's conversion: a field resource can
/// carry a valid override alongside an unrecognisable TTL state (or the reverse), and failing on
/// one bad half would hide the other, valid half from the diff and re-plan a change to it on
/// every sync.
///
/// [`ProtoField`]: gcloud_sdk::google::firestore::admin::v1::Field
#[derive(Debug, PartialEq, Clone)]
pub enum FirestoreFieldOverrideOutcome {
    /// The field carries an `index_config`, but it is inherited from an ancestor field
    /// (`uses_ancestor_config`), not an explicit override. Not an override a declaration can be
    /// compared against - the same as [`FirestoreListedField::index_override`] being `None`
    /// (no `index_config` at all), which is why the diff treats the two alike.
    Inherited,
    /// An explicit, non-inherited override.
    Explicit(FirestoreExplicitFieldOverride),
    /// The listed `index_config` carries data this crate's domain model cannot represent (an
    /// unspecified or unknown order, array config, vector dimension, query scope or API scope).
    /// Carries why, for [`FirestoreUnrecognisedIndexItem::reason`].
    Unrecognised(String),
}

/// A field resource's TTL configuration, as read from a listed [`ProtoField`] that carries one.
///
/// [`ProtoField`]: gcloud_sdk::google::firestore::admin::v1::Field
#[derive(Debug, PartialEq, Clone)]
pub enum FirestoreFieldTtlOutcome {
    /// TTL is configured, in the given lifecycle state.
    Configured(FirestoreFieldTtlState),
    /// The listed `ttl_config` carries a state this crate's domain model cannot represent.
    /// Carries why, for [`FirestoreUnrecognisedIndexItem::reason`]. Report-only, the same as any
    /// other unrecognised item: the planner never enables, disables or otherwise acts on it.
    Unrecognised(String),
}

/// One field resource Firestore has listed for the owned collection group, because it carries an
/// explicit single-field index override, a TTL configuration, or both.
#[derive(Debug, PartialEq, Clone)]
pub struct FirestoreListedField {
    /// The resource name Firestore assigned this field, for logging or an update call.
    pub name: String,
    /// The field's path within a document, parsed from `name`.
    pub field_path: String,
    /// The field's single-field index configuration, or `None` when the field carries no
    /// `index_config` at all.
    pub index_override: Option<FirestoreFieldOverrideOutcome>,
    /// The field's TTL configuration, or `None` when the field carries no `ttl_config` at all.
    pub ttl: Option<FirestoreFieldTtlOutcome>,
}

/// One listed index or field resource this crate's domain model cannot represent, kept for
/// visibility instead of being silently dropped.
///
/// Covers a search index, a MongoDB-compat or Datastore-mode API scope, a `COLLECTION_RECURSIVE`
/// query scope, and an unspecified field order - none of which a declared [`FirestoreCompositeIndex`]
/// or [`FirestoreFieldOverride`] can express. The planner never proposes deleting or reverting
/// one of these, even when pruning, because it cannot know that doing so is what the declaration
/// intends.
#[derive(Debug, PartialEq, Clone)]
pub struct FirestoreUnrecognisedIndexItem {
    /// The resource name Firestore assigned it.
    pub name: String,
    /// Why this crate could not convert it into a domain value.
    pub reason: String,
}

/// One collection group's declared composite indexes, single-field overrides and TTL policy.
///
/// A statement owns exactly this one collection group: [`FirestoreIndexSyncOptions::prune`]
/// never reaches an index, override or TTL field on any other group. Several groups need
/// several statements.
#[derive(Debug, PartialEq, Clone, Builder)]
pub struct FirestoreIndexParams {
    /// The collection group this statement owns.
    pub collection_group: FirestoreCollectionId,
    /// The declared composite indexes.
    #[default = "Vec::new()"]
    pub composite_indexes: Vec<FirestoreCompositeIndex>,
    /// The declared single-field index overrides.
    #[default = "Vec::new()"]
    pub field_overrides: Vec<FirestoreFieldOverride>,
    /// The field paths whose timestamp should enable document TTL.
    #[default = "Vec::new()"]
    pub ttl_fields: Vec<String>,
}

/// How long long-running Firestore operations are polled for before giving up, shared by index
/// sync and bulk delete.
///
/// `timeout` sets one deadline, fixed when the call starts: every wait of the call ends by it,
/// including an index sync's waits between writes that depend on each other. Until then, each
/// round polls every pending operation and then sleeps `poll_interval`, or only until the
/// deadline when that comes first, so the last round goes out at the deadline itself. One poll
/// may take up to 10 seconds to answer, or the whole `timeout` when that is shorter; a poll that
/// takes longer is abandoned and sent again next round. So a wait that times out returns at most
/// that long after the deadline, with an error naming the operations still pending. A `timeout`
/// too long to represent, such as `Duration::MAX`, means no practical deadline.
#[derive(Debug, PartialEq, Clone, Builder)]
pub struct FirestoreOperationWaitOptions {
    /// How long after the call starts every wait of it must end.
    pub timeout: Duration,
    /// The pause between two rounds of polls.
    #[default = "Duration::from_secs(5)"]
    pub poll_interval: Duration,
}

/// Options controlling how `.sync()` reconciles a declared [`FirestoreIndexParams`] with
/// Firestore.
#[derive(Debug, PartialEq, Clone, Builder)]
pub struct FirestoreIndexSyncOptions {
    /// When set, also deletes undeclared composite indexes, reverts undeclared field overrides,
    /// and disables undeclared TTL fields in the owned collection group. Otherwise undeclared
    /// items are only reported.
    #[default = "false"]
    pub prune: bool,
    /// Whether, and how long, to wait for started changes to finish. `Some` waits for every
    /// started change to reach a terminal state, and its timeout bounds the whole sync. `None`
    /// returns once the last change is requested; the waits between writes that depend on each
    /// other still happen, under a 30-minute deadline for the whole sync.
    #[default = "None"]
    pub wait: Option<FirestoreOperationWaitOptions>,
}

/// The outcome of comparing a declared [`FirestoreIndexParams`] against one collection group's
/// existing indexes, field overrides and TTL configuration, under the given
/// [`FirestoreIndexSyncOptions::prune`] setting.
///
/// Returned by the fluent `.plan()` terminal, and by `.sync()`'s internal planning step before it
/// writes anything. Every undeclared item lands in exactly one of two lists: the one `.sync()`
/// acts on when pruning (`delete_indexes`, `revert_fields`, `disable_ttl`), or the one it keeps
/// and only reports otherwise (`kept_undeclared_*`). So a plan made with `.prune_undeclared()`
/// shows exactly what a pruning sync would do.
#[derive(Debug, Default, PartialEq, Clone)]
pub struct FirestoreIndexPlan {
    /// Declared composite indexes that match nothing listed; `.sync()` creates these.
    pub create_indexes: Vec<FirestoreCompositeIndex>,
    /// Declared composite indexes matched to a listed index in state `READY`.
    pub unchanged: Vec<FirestoreCompositeIndex>,
    /// Declared composite indexes matched to a listed index in state `CREATING`.
    pub pending: Vec<FirestoreCompositeIndex>,
    /// Declared composite indexes matched to a listed index in state `NEEDS_REPAIR`. These are
    /// reported only; `.sync()` never deletes or recreates them.
    pub needs_repair: Vec<FirestoreCompositeIndex>,
    /// Listed composite indexes with no declared match, in the owned collection group, that
    /// `.sync()` deletes because `prune` is set.
    pub delete_indexes: Vec<FirestoreListedCompositeIndex>,
    /// Listed composite indexes with no declared match, in the owned collection group, kept
    /// because `prune` is not set.
    pub kept_undeclared_indexes: Vec<FirestoreListedCompositeIndex>,
    /// Declared field overrides whose listed configuration differs from the declaration, or is
    /// absent; `.sync()` writes these.
    pub update_fields: Vec<FirestoreFieldOverride>,
    /// Declared field overrides matched to a listed override Firestore is already reverting
    /// (`reverting: true`, an in-flight change back to the ancestor's configuration). Classified
    /// as pending, not unchanged: once the revert completes the field will no longer carry this
    /// override, and only the *next* sync writes it back. `.sync()` never writes over one of
    /// these - doing so would race Firestore's own in-flight change.
    pub reverting_fields: Vec<FirestoreListedField>,
    /// Listed field overrides with no declared match, in the owned collection group, that
    /// `.sync()` reverts to the ancestor's configuration because `prune` is set.
    pub revert_fields: Vec<FirestoreListedField>,
    /// Listed field overrides with no declared match, in the owned collection group, kept because
    /// `prune` is not set.
    pub kept_undeclared_fields: Vec<FirestoreListedField>,
    /// Declared TTL fields with no TTL configuration listed; `.sync()` enables these.
    pub enable_ttl: Vec<String>,
    /// Declared TTL fields matched to a listed TTL configuration already in state `ACTIVE`.
    pub unchanged_ttl: Vec<String>,
    /// Declared TTL fields matched to a listed TTL configuration still in state `CREATING`.
    pub pending_ttl: Vec<String>,
    /// Declared TTL fields matched to a listed TTL configuration in state `NEEDS_REPAIR`.
    pub needs_repair_ttl: Vec<String>,
    /// Listed TTL fields with no declaration, in the owned collection group, that `.sync()`
    /// disables because `prune` is set.
    pub disable_ttl: Vec<FirestoreListedField>,
    /// Listed TTL fields with no declaration, in the owned collection group, kept because `prune`
    /// is not set.
    pub kept_undeclared_ttl: Vec<FirestoreListedField>,
    /// Listed indexes or fields this crate's domain model cannot represent; never planned for
    /// deletion or revert, even when pruning.
    pub unrecognised: Vec<FirestoreUnrecognisedIndexItem>,
    /// Why this plan did nothing without contacting Firestore; `None` when it ran. Mirrors
    /// [`FirestoreIndexSyncReport::skipped`], so a plan made against the emulator carries the
    /// same explicit marker a sync against it reports, rather than the plain default a caller
    /// could otherwise mistake for "nothing to do".
    pub skipped: Option<FirestoreIndexSyncSkipReason>,
}

/// The result of `.sync()`: what it changed, what it left alone, and what it found undeclared.
///
/// Every list carries the resource a caller would log or use to fail a deploy on; filled in by
/// [`FirestoreDb`](crate::FirestoreDb)'s index management.
#[derive(Debug, Default, PartialEq, Clone)]
pub struct FirestoreIndexSyncReport {
    /// Composite indexes created by this sync.
    pub created_indexes: Vec<FirestoreCompositeIndex>,
    /// Field overrides written by this sync.
    pub updated_fields: Vec<FirestoreFieldOverride>,
    /// TTL fields enabled by this sync.
    pub enabled_ttl: Vec<String>,
    /// Declared TTL fields already active before this sync ran.
    pub unchanged_ttl: Vec<String>,
    /// Composite indexes matched to a listed index already in state `READY`.
    pub unchanged: Vec<FirestoreCompositeIndex>,
    /// Composite indexes matched to a listed index still in state `CREATING`.
    pub pending: Vec<FirestoreCompositeIndex>,
    /// Composite indexes matched to a listed index in state `NEEDS_REPAIR`, reported only.
    pub needs_repair: Vec<FirestoreCompositeIndex>,
    /// Declared TTL fields matched to a listed TTL configuration still in state `CREATING`.
    pub pending_ttl: Vec<String>,
    /// Declared TTL fields matched to a listed TTL configuration in state `NEEDS_REPAIR`,
    /// reported only.
    pub needs_repair_ttl: Vec<String>,
    /// Undeclared composite indexes this sync deleted, because `prune` was set. Includes one
    /// another writer deleted first: the two converge on the same absence, and the log line for
    /// that delete, not this list, is where the two are told apart.
    pub deleted_indexes: Vec<FirestoreListedCompositeIndex>,
    /// Undeclared composite indexes a pruning sync planned to delete but left in place, and why;
    /// `None` when it withheld no delete.
    pub withheld_deletes: Option<FirestoreIndexDeletesWithheld>,
    /// Undeclared field overrides this sync reverted to automatic indexing, because `prune` was
    /// set. Includes one another writer reverted first: the two converge on the same state, and
    /// the log line for that write, not this list, is where the two are told apart.
    pub reverted_fields: Vec<FirestoreListedField>,
    /// Undeclared TTL fields this sync disabled, because `prune` was set. Includes one another
    /// writer disabled first: the two converge on the same state, and the log line for that
    /// write, not this list, is where the two are told apart.
    pub disabled_ttl: Vec<FirestoreListedField>,
    /// Undeclared composite indexes left alone, because `prune` was not set.
    pub kept_undeclared_indexes: Vec<FirestoreListedCompositeIndex>,
    /// Undeclared field overrides left alone, because `prune` was not set.
    pub kept_undeclared_fields: Vec<FirestoreListedField>,
    /// Undeclared TTL fields left alone, because `prune` was not set.
    pub kept_undeclared_ttl: Vec<FirestoreListedField>,
    /// Listed indexes or fields this crate's domain model cannot represent; never deleted or
    /// reverted, even when pruning.
    pub unrecognised: Vec<FirestoreUnrecognisedIndexItem>,
    /// Why this sync did nothing without contacting Firestore; `None` when it ran.
    pub skipped: Option<FirestoreIndexSyncSkipReason>,
    /// How long the sync and each of its phases took.
    pub timings: FirestoreIndexSyncTimings,
}

/// Undeclared composite indexes a pruning `.sync()` planned to delete but left in place, because
/// deleting them could have left queries without an index.
#[derive(Debug, PartialEq, Clone)]
pub struct FirestoreIndexDeletesWithheld {
    /// The undeclared indexes left in place.
    pub indexes: Vec<FirestoreListedCompositeIndex>,
    /// Why they were left in place.
    pub reason: FirestoreIndexDeletesWithheldReason,
}

/// Why a pruning `.sync()` sent none of its planned index deletes.
#[derive(Debug, PartialEq, Clone)]
pub enum FirestoreIndexDeletesWithheldReason {
    /// `CreateIndex` answered `ALREADY_EXISTS` for these declared indexes, although the listing
    /// matched none of them. Firestore holds an index it counts as equivalent, which may be one of
    /// the indexes planned for deletion.
    AlreadyExists(Vec<FirestoreCompositeIndex>),
    /// These indexes, created by the same sync, had not finished building: an operation failed,
    /// or the sync's deadline passed first. A delete sent then could remove the index queries use
    /// while its replacement cannot serve them yet.
    CreatesUnfinished(Vec<FirestoreCompositeIndex>),
}

/// Why a `.sync()` returned without contacting Firestore.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum FirestoreIndexSyncSkipReason {
    /// The client talks to the Firestore emulator, which does not implement the admin API.
    Emulator,
}

/// How long a `.sync()` took, in total and per phase. A phase is `None` when it did not run: all
/// of them for a skipped sync, and `wait` when the caller did not ask to wait.
#[derive(Debug, PartialEq, Eq, Clone, Default)]
pub struct FirestoreIndexSyncTimings {
    /// The whole call.
    pub total: Duration,
    /// Listing the group's indexes and fields.
    pub list: Option<Duration>,
    /// Sending the changes, including any wait between two writes that depend on each other and
    /// the wait for new indexes before a pruning sync deletes old ones.
    pub apply: Option<Duration>,
    /// Waiting for the started changes to finish.
    pub wait: Option<Duration>,
}

/// The maximum number of fields Firestore allows on one composite index, `__name__` included.
const MAX_INDEX_FIELDS_WITH_IMPLIED_NAME: usize = 100;

/// Checks the structural rules a declared [`FirestoreIndexParams`] must satisfy, independent of
/// what Firestore currently has.
///
/// # Errors
/// Returns [`FirestoreError::InvalidParametersError`] if a composite index has fewer than two
/// fields (a lone vector field excepted), more than 100 fields counting an implied `__name__`,
/// more than one vector field, a vector field that is not last, a vector dimension outside
/// `1..=2048`, an empty field path, or duplicates an earlier declared index once a trailing
/// `__name__` is normalised away; if a field override path is declared more than once, declares
/// the same single-field index twice, declares a vector index, or has an empty path; or if more
/// than one TTL field is declared, a TTL path is empty, or a TTL path repeats.
pub(crate) fn validate_index_params(params: &FirestoreIndexParams) -> FirestoreResult<()> {
    validate_collection_group(&params.collection_group)?;
    validate_composite_indexes(&params.composite_indexes)?;
    validate_field_overrides(&params.field_overrides)?;
    validate_ttl_fields(&params.ttl_fields)?;
    Ok(())
}

/// Rejects the collection group IDs Firestore reserves for itself: the literal `-` (a wildcard
/// segment in a document path, never a real collection group), `__default__` (the database-wide
/// configuration every collection group inherits from unless overridden), and any other ID of the
/// shape `__*__` (Firestore's reserved namespace for system collection groups). A statement that
/// named one of these would list and modify the reserved group's own resources instead of the
/// caller's collection - measured against the real service, 2026-09-26: a
/// `.collection_group("__default__")` sync issued
/// `UpdateField .../collectionGroups/__default__/fields/*`, changing database-wide defaults no
/// statement should be able to reach.
///
/// [`FirestoreCollectionId::new`] accepts these IDs on purpose (see its module docs), because a
/// bare document or collection reference to them is legitimate; only naming one as the group a
/// whole statement *owns* is not.
pub(crate) fn validate_collection_group(
    collection_group: &FirestoreCollectionId,
) -> FirestoreResult<()> {
    let id = collection_group.as_str();
    let is_reserved = id == "-" || (id.len() >= 4 && id.starts_with("__") && id.ends_with("__"));
    if is_reserved {
        return Err(FirestoreError::invalid_parameters(
            "collection_group",
            format!(
                "\"{id}\" is a collection group ID Firestore reserves (\"-\", or __*__ such as \
                 __default__); index management must not target it"
            ),
        ));
    }
    Ok(())
}

fn validate_composite_indexes(indexes: &[FirestoreCompositeIndex]) -> FirestoreResult<()> {
    for (position, index) in indexes.iter().enumerate() {
        let vector_positions: Vec<usize> = index
            .fields
            .iter()
            .enumerate()
            .filter(|(_, field)| matches!(field.mode, FirestoreIndexFieldMode::Vector(_)))
            .map(|(field_position, _)| field_position)
            .collect();

        let is_lone_vector_field = index.fields.len() == 1 && vector_positions == [0];
        if index.fields.len() < 2 && !is_lone_vector_field {
            return Err(FirestoreError::invalid_parameters(
                "composite_indexes",
                format!(
                    "index {position} needs at least two fields, or exactly one vector field, has {}",
                    index.fields.len()
                ),
            ));
        }

        if index.fields.iter().any(|field| field.field_path.is_empty()) {
            return Err(FirestoreError::invalid_parameters(
                "composite_indexes",
                format!("index {position} has a field with an empty path"),
            ));
        }

        let declares_implied_name = index
            .fields
            .iter()
            .any(|field| field.field_path == IMPLIED_NAME_FIELD);
        let max_fields = if declares_implied_name {
            MAX_INDEX_FIELDS_WITH_IMPLIED_NAME
        } else {
            MAX_INDEX_FIELDS_WITH_IMPLIED_NAME - 1
        };
        if index.fields.len() > max_fields {
            return Err(FirestoreError::invalid_parameters(
                "composite_indexes",
                format!(
                    "index {position} declares {} fields; Firestore allows at most {max_fields} \
                     (100 including the __name__ field it appends)",
                    index.fields.len()
                ),
            ));
        }

        for (earlier_position, earlier) in indexes.iter().enumerate().take(position) {
            // Checked both ways: `composite_index_matches` only ignores `__name__` on its
            // second (`listed`) argument, and either of the two declarations may be the one
            // that states it explicitly.
            if super::index_diff::composite_index_matches(index, earlier)
                || super::index_diff::composite_index_matches(earlier, index)
            {
                return Err(FirestoreError::invalid_parameters(
                    "composite_indexes",
                    format!(
                        "index {position} duplicates index {earlier_position} once an implicit \
                         __name__ field is ignored"
                    ),
                ));
            }
        }

        match vector_positions.as_slice() {
            [] => {}
            [only] if *only == index.fields.len() - 1 => {
                if let FirestoreIndexFieldMode::Vector(vector) = &index.fields[*only].mode {
                    validate_vector_dimension(vector.dimension, "composite_indexes")?;
                }
            }
            [only] => {
                return Err(FirestoreError::invalid_parameters(
                    "composite_indexes",
                    format!(
                        "index {position}'s vector field must be last, was at position {only} of {}",
                        index.fields.len()
                    ),
                ));
            }
            multiple => {
                return Err(FirestoreError::invalid_parameters(
                    "composite_indexes",
                    format!(
                        "index {position} has {} vector fields, at most one is allowed",
                        multiple.len()
                    ),
                ));
            }
        }
    }
    Ok(())
}

fn validate_vector_dimension(dimension: u32, field: &'static str) -> FirestoreResult<()> {
    if dimension == 0 || dimension > 2048 {
        return Err(FirestoreError::invalid_parameters(
            field,
            format!("vector dimension must be between 1 and 2048, was {dimension}"),
        ));
    }
    Ok(())
}

fn validate_field_overrides(overrides: &[FirestoreFieldOverride]) -> FirestoreResult<()> {
    let mut seen_targets: HashSet<&FirestoreFieldOverrideTarget> = HashSet::new();
    for field_override in overrides {
        match &field_override.target {
            FirestoreFieldOverrideTarget::Field(path) if path.is_empty() => {
                return Err(FirestoreError::invalid_parameters(
                    "field_overrides",
                    "a field override's field path must not be empty",
                ));
            }
            FirestoreFieldOverrideTarget::Field(path) if path == ALL_FIELDS_PATH => {
                return Err(FirestoreError::invalid_parameters(
                    "field_overrides",
                    "field path \"*\" is reserved; declare it with all_fields() instead of \
                     field(\"*\")",
                ));
            }
            _ => {}
        }
        if !seen_targets.insert(&field_override.target) {
            return Err(FirestoreError::invalid_parameters(
                "field_overrides",
                format!(
                    "{} is declared more than once",
                    field_override.target.as_str()
                ),
            ));
        }
        if super::index_diff::override_index_set(&field_override.indexes).len()
            != field_override.indexes.len()
        {
            return Err(FirestoreError::invalid_parameters(
                "field_overrides",
                format!(
                    "{} declares the same single-field index more than once",
                    field_override.target.as_str()
                ),
            ));
        }
        for index in &field_override.indexes {
            if matches!(index.mode, FirestoreIndexFieldMode::Vector(_)) {
                return Err(FirestoreError::invalid_parameters(
                    "field_overrides",
                    format!(
                        "{} declares a vector index, which Firestore does not support as a \
                         single-field override",
                        field_override.target.as_str()
                    ),
                ));
            }
        }
    }
    Ok(())
}

/// Firestore allows at most one TTL field per collection group.
///
/// <https://firebase.google.com/docs/firestore/ttl>: "You can mark only one field per collection
/// group as a TTL field."
fn validate_ttl_fields(ttl_fields: &[String]) -> FirestoreResult<()> {
    for path in ttl_fields {
        if path.is_empty() {
            return Err(FirestoreError::invalid_parameters(
                "ttl_fields",
                "a TTL field path must not be empty",
            ));
        }
    }
    if ttl_fields.len() > 1 {
        return Err(FirestoreError::invalid_parameters(
            "ttl_fields",
            format!(
                "a collection group may have at most one TTL field, {} were declared",
                ttl_fields.len()
            ),
        ));
    }
    Ok(())
}

/// Writes `label: <count>`, then one indented line per item's [`Display`], or nothing at all when
/// `items` is empty. Shared by every section of [`Display for FirestoreIndexPlan`],
/// [`Display for FirestoreIndexSyncReport`] and the existing-state summary in
/// `db::admin::indexes`, so a log line built from the same items never disagrees with what these
/// types print, and an empty section never crowds out the ones that have something to say.
pub(crate) fn write_section<T: Display>(
    f: &mut Formatter<'_>,
    label: &str,
    items: &[T],
) -> fmt::Result {
    if items.is_empty() {
        return Ok(());
    }
    writeln!(f, "  {label}: {}", items.len())?;
    for item in items {
        writeln!(f, "    {item}")?;
    }
    Ok(())
}

/// Writes each item's [`Display`], separated by `", "`, with no wrapping punctuation of its own -
/// callers add whatever brackets their own format uses. Shared by every place that prints an
/// index or override's field list, so the separator never drifts between call sites.
fn write_comma_joined<T: Display>(f: &mut Formatter<'_>, items: &[T]) -> fmt::Result {
    for (position, item) in items.iter().enumerate() {
        if position > 0 {
            write!(f, ", ")?;
        }
        write!(f, "{item}")?;
    }
    Ok(())
}

impl Display for FirestoreIndexQueryScope {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            FirestoreIndexQueryScope::Collection => "COLLECTION",
            FirestoreIndexQueryScope::AllDescendants => "COLLECTION_GROUP",
        })
    }
}

impl Display for FirestoreIndexFieldMode {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            FirestoreIndexFieldMode::Order(FirestoreQueryDirection::Ascending) => {
                f.write_str("ASC")
            }
            FirestoreIndexFieldMode::Order(FirestoreQueryDirection::Descending) => {
                f.write_str("DESC")
            }
            FirestoreIndexFieldMode::ArrayContains => f.write_str("CONTAINS"),
            FirestoreIndexFieldMode::Vector(vector) => write!(f, "VECTOR({})", vector.dimension),
        }
    }
}

impl Display for FirestoreIndexField {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{} {}", self.field_path, self.mode)
    }
}

impl Display for FirestoreCompositeIndex {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "[{}] (", self.query_scope)?;
        write_comma_joined(f, &self.fields)?;
        write!(f, ")")
    }
}

impl Display for FirestoreIndexState {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            FirestoreIndexState::Creating => "CREATING",
            FirestoreIndexState::Ready => "READY",
            FirestoreIndexState::NeedsRepair => "NEEDS_REPAIR",
        })
    }
}

impl Display for FirestoreListedCompositeIndex {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{} {} ({})", self.index, self.state, self.name)
    }
}

impl Display for FirestoreFieldOverrideIndex {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "[{}] {}", self.query_scope, self.mode)
    }
}

impl Display for FirestoreFieldOverrideTarget {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl Display for FirestoreFieldOverride {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.target)?;
        if self.indexes.is_empty() {
            return f.write_str(" EXEMPT");
        }
        write!(f, " [")?;
        write_comma_joined(f, &self.indexes)?;
        write!(f, "]")
    }
}

impl Display for FirestoreFieldTtlState {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            FirestoreFieldTtlState::Creating => "CREATING",
            FirestoreFieldTtlState::Active => "ACTIVE",
            FirestoreFieldTtlState::NeedsRepair => "NEEDS_REPAIR",
        })
    }
}

impl Display for FirestoreListedField {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.field_path)?;
        match &self.index_override {
            None | Some(FirestoreFieldOverrideOutcome::Inherited) => {}
            Some(FirestoreFieldOverrideOutcome::Explicit(explicit)) => {
                if explicit.indexes.is_empty() {
                    write!(f, " EXEMPT")?;
                } else {
                    write!(f, " [")?;
                    write_comma_joined(f, &explicit.indexes)?;
                    write!(f, "]")?;
                }
                if explicit.reverting {
                    write!(f, " (reverting)")?;
                }
            }
            Some(FirestoreFieldOverrideOutcome::Unrecognised(reason)) => {
                write!(f, " override unrecognised: {reason}")?;
            }
        }
        match &self.ttl {
            None => {}
            Some(FirestoreFieldTtlOutcome::Configured(state)) => write!(f, " ttl={state}")?,
            Some(FirestoreFieldTtlOutcome::Unrecognised(reason)) => {
                write!(f, " ttl unrecognised: {reason}")?;
            }
        }
        write!(f, " ({})", self.name)
    }
}

impl Display for FirestoreUnrecognisedIndexItem {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.name, self.reason)
    }
}

impl Display for FirestoreIndexPlan {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let anything_to_report = !self.create_indexes.is_empty()
            || !self.update_fields.is_empty()
            || !self.reverting_fields.is_empty()
            || !self.enable_ttl.is_empty()
            || !self.delete_indexes.is_empty()
            || !self.revert_fields.is_empty()
            || !self.disable_ttl.is_empty()
            || !self.kept_undeclared_indexes.is_empty()
            || !self.kept_undeclared_fields.is_empty()
            || !self.kept_undeclared_ttl.is_empty()
            || !self.needs_repair.is_empty()
            || !self.needs_repair_ttl.is_empty()
            || !self.unrecognised.is_empty();

        if !anything_to_report {
            writeln!(
                f,
                "Firestore index plan: no changes ({} unchanged, {} pending, {} ttl unchanged)",
                self.unchanged.len(),
                self.pending.len(),
                self.unchanged_ttl.len()
            )?;
            if let Some(reason) = &self.skipped {
                writeln!(f, "  skipped: {reason}")?;
            }
            return Ok(());
        }

        writeln!(f, "Firestore index plan:")?;
        write_section(f, "create_indexes", &self.create_indexes)?;
        write_section(f, "update_field_overrides", &self.update_fields)?;
        write_section(
            f,
            "reverting_field_overrides (revert in progress, no write planned)",
            &self.reverting_fields,
        )?;
        write_section(f, "disable_ttl", &self.disable_ttl)?;
        write_section(f, "enable_ttl", &self.enable_ttl)?;
        write_section(f, "delete_indexes", &self.delete_indexes)?;
        write_section(f, "revert_field_overrides", &self.revert_fields)?;
        write_section(
            f,
            "kept_undeclared_indexes (prune_undeclared() would delete)",
            &self.kept_undeclared_indexes,
        )?;
        write_section(
            f,
            "kept_undeclared_fields (prune_undeclared() would revert)",
            &self.kept_undeclared_fields,
        )?;
        write_section(
            f,
            "kept_undeclared_ttl (prune_undeclared() would disable)",
            &self.kept_undeclared_ttl,
        )?;
        write_section(f, "needs_repair", &self.needs_repair)?;
        write_section(f, "needs_repair_ttl", &self.needs_repair_ttl)?;
        write_section(f, "unrecognised, never pruned", &self.unrecognised)?;
        if !self.unchanged.is_empty() || !self.pending.is_empty() || !self.unchanged_ttl.is_empty()
        {
            writeln!(
                f,
                "  unchanged: {}, pending: {}, ttl unchanged: {}",
                self.unchanged.len(),
                self.pending.len(),
                self.unchanged_ttl.len()
            )?;
        }
        if let Some(reason) = &self.skipped {
            writeln!(f, "  skipped: {reason}")?;
        }
        Ok(())
    }
}

impl Display for FirestoreIndexSyncReport {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        writeln!(f, "Firestore index sync report:")?;
        write_section(f, "created_indexes", &self.created_indexes)?;
        write_section(f, "updated_fields", &self.updated_fields)?;
        write_section(f, "enabled_ttl", &self.enabled_ttl)?;
        write_section(f, "unchanged_ttl", &self.unchanged_ttl)?;
        write_section(f, "unchanged", &self.unchanged)?;
        write_section(f, "pending", &self.pending)?;
        write_section(f, "needs_repair", &self.needs_repair)?;
        write_section(f, "pending_ttl", &self.pending_ttl)?;
        write_section(f, "needs_repair_ttl", &self.needs_repair_ttl)?;
        write_section(f, "deleted_indexes", &self.deleted_indexes)?;
        if let Some(withheld) = &self.withheld_deletes {
            writeln!(
                f,
                "  withheld_deletes: {}, because {}",
                withheld.indexes.len(),
                withheld.reason
            )?;
            for index in &withheld.indexes {
                writeln!(f, "    {index}")?;
            }
        }
        write_section(f, "reverted_fields", &self.reverted_fields)?;
        write_section(f, "disabled_ttl", &self.disabled_ttl)?;
        write_section(f, "kept_undeclared_indexes", &self.kept_undeclared_indexes)?;
        write_section(f, "kept_undeclared_fields", &self.kept_undeclared_fields)?;
        write_section(f, "kept_undeclared_ttl", &self.kept_undeclared_ttl)?;
        write_section(f, "unrecognised", &self.unrecognised)?;
        if let Some(reason) = &self.skipped {
            writeln!(f, "  skipped: {reason}")?;
        }
        writeln!(f, "  timings: {}", self.timings)
    }
}

impl Display for FirestoreIndexDeletesWithheldReason {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            FirestoreIndexDeletesWithheldReason::AlreadyExists(indexes) => {
                write!(f, "CreateIndex answered ALREADY_EXISTS for ")?;
                write_comma_joined(f, indexes)
            }
            FirestoreIndexDeletesWithheldReason::CreatesUnfinished(indexes) => {
                write!(f, "these new indexes had not finished building: ")?;
                write_comma_joined(f, indexes)
            }
        }
    }
}

impl Display for FirestoreIndexSyncSkipReason {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            FirestoreIndexSyncSkipReason::Emulator => {
                write!(f, "the Firestore emulator does not implement the admin API")
            }
        }
    }
}

impl Display for FirestoreIndexSyncTimings {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "total {} ms", self.total.as_millis())?;
        for (phase, duration) in [
            ("list", self.list),
            ("apply", self.apply),
            ("wait", self.wait),
        ] {
            if let Some(duration) = duration {
                write!(f, ", {phase} {} ms", duration.as_millis())?;
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_field_path_has_one_canonical_spelling() {
        for (written, canonical) in [
            ("x", "x"),
            ("`x`", "x"),
            ("a.`b`", "a.b"),
            ("`a`.b", "a.b"),
            ("`my-field`", "`my-field`"),
            ("my-field", "`my-field`"),
            ("`a/b`.c", "`a/b`.c"),
            ("`a\\`b`", "`a\\`b`"),
            ("`back\\\\slash`", "`back\\\\slash`"),
            ("`_ok9`", "_ok9"),
            ("`9lives`", "`9lives`"),
            ("`__name__`", "__name__"),
            ("*", "*"),
        ] {
            assert_eq!(
                CanonicalFieldPath::from(written).as_str(),
                canonical,
                "{written}"
            );
        }
    }

    #[test]
    fn a_field_path_outside_the_grammar_is_kept_as_written() {
        for written in ["`open", "a..b", "a.", "``", "a`b"] {
            assert_eq!(CanonicalFieldPath::from(written).as_str(), written);
        }
    }

    #[test]
    fn a_field_resource_name_yields_its_canonical_field_path() {
        let name = "projects/p/databases/fields/collectionGroups/users/fields/`a/b`.`c`";
        assert_eq!(
            CanonicalFieldPath::from_field_resource_name(name)
                .unwrap()
                .as_str(),
            "`a/b`.c"
        );
        assert!(CanonicalFieldPath::from_field_resource_name("projects/p/other/x").is_err());
    }

    fn field(path: &str, mode: FirestoreIndexFieldMode) -> FirestoreIndexField {
        FirestoreIndexField::new(path.to_string(), mode)
    }

    fn asc(path: &str) -> FirestoreIndexField {
        field(
            path,
            FirestoreIndexFieldMode::Order(FirestoreQueryDirection::Ascending),
        )
    }

    #[test]
    fn composite_index_needs_at_least_two_fields() {
        let index = FirestoreCompositeIndex::new(vec![asc("a")]);
        let err = validate_composite_indexes(&[index]).unwrap_err();
        assert!(err.to_string().contains("at least two fields"));
    }

    #[test]
    fn composite_index_with_two_fields_is_valid() {
        let index = FirestoreCompositeIndex::new(vec![asc("a"), asc("b")]);
        assert!(validate_composite_indexes(&[index]).is_ok());
    }

    #[test]
    fn vector_field_must_be_last() {
        let index = FirestoreCompositeIndex::new(vec![
            field(
                "v",
                FirestoreIndexFieldMode::Vector(FirestoreVectorIndexConfig::new(8)),
            ),
            asc("b"),
        ]);
        let err = validate_composite_indexes(&[index]).unwrap_err();
        assert!(err.to_string().contains("must be last"));
    }

    #[test]
    fn vector_field_last_is_valid() {
        let index = FirestoreCompositeIndex::new(vec![
            asc("a"),
            field(
                "v",
                FirestoreIndexFieldMode::Vector(FirestoreVectorIndexConfig::new(8)),
            ),
        ]);
        assert!(validate_composite_indexes(&[index]).is_ok());
    }

    #[test]
    fn at_most_one_vector_field() {
        let index = FirestoreCompositeIndex::new(vec![
            field(
                "v1",
                FirestoreIndexFieldMode::Vector(FirestoreVectorIndexConfig::new(8)),
            ),
            field(
                "v2",
                FirestoreIndexFieldMode::Vector(FirestoreVectorIndexConfig::new(8)),
            ),
        ]);
        let err = validate_composite_indexes(&[index]).unwrap_err();
        assert!(err.to_string().contains("at most one is allowed"));
    }

    #[test]
    fn vector_dimension_must_be_in_range() {
        for bad_dimension in [0u32, 2049] {
            let index = FirestoreCompositeIndex::new(vec![
                asc("a"),
                field(
                    "v",
                    FirestoreIndexFieldMode::Vector(FirestoreVectorIndexConfig::new(bad_dimension)),
                ),
            ]);
            let err = validate_composite_indexes(&[index]).unwrap_err();
            assert!(err.to_string().contains("between 1 and 2048"));
        }

        let index = FirestoreCompositeIndex::new(vec![
            asc("a"),
            field(
                "v",
                FirestoreIndexFieldMode::Vector(FirestoreVectorIndexConfig::new(2048)),
            ),
        ]);
        assert!(validate_composite_indexes(&[index]).is_ok());
    }

    #[test]
    fn duplicate_field_override_path_is_rejected() {
        let overrides = vec![
            FirestoreFieldOverride {
                target: FirestoreFieldOverrideTarget::Field("tags".to_string()),
                indexes: vec![],
            },
            FirestoreFieldOverride {
                target: FirestoreFieldOverrideTarget::Field("tags".to_string()),
                indexes: vec![],
            },
        ];
        let err = validate_field_overrides(&overrides).unwrap_err();
        assert!(err.to_string().contains("declared more than once"));
    }

    #[test]
    fn exempt_and_empty_indexes_are_the_same_and_accepted() {
        let overrides = vec![FirestoreFieldOverride {
            target: FirestoreFieldOverrideTarget::Field("bio".to_string()),
            indexes: vec![],
        }];
        assert!(validate_field_overrides(&overrides).is_ok());
    }

    #[test]
    fn empty_declaration_is_valid() {
        let params = FirestoreIndexParams::new(FirestoreCollectionId::from_static("users"));
        assert!(validate_index_params(&params).is_ok());
        assert!(params.composite_indexes.is_empty());
        assert!(params.field_overrides.is_empty());
        assert!(params.ttl_fields.is_empty());
    }

    #[test]
    fn default_collection_group_is_rejected() {
        // Firestore's database-wide defaults every collection group inherits from unless
        // overridden - a statement must never be able to reach them.
        let params = FirestoreIndexParams::new(FirestoreCollectionId::from_static("__default__"));
        let err = validate_index_params(&params).unwrap_err();
        assert!(err.to_string().contains("__default__"));
    }

    #[test]
    fn dash_collection_group_is_rejected() {
        let params = FirestoreIndexParams::new(FirestoreCollectionId::from_static("-"));
        let err = validate_index_params(&params).unwrap_err();
        assert!(err.to_string().contains("reserves"));
    }

    #[test]
    fn other_reserved_shaped_collection_group_is_rejected() {
        let params = FirestoreIndexParams::new(FirestoreCollectionId::from_static("__x__"));
        let err = validate_index_params(&params).unwrap_err();
        assert!(err.to_string().contains("__x__"));
    }

    #[test]
    fn ordinary_collection_group_is_accepted() {
        let params = FirestoreIndexParams::new(FirestoreCollectionId::from_static("users"));
        assert!(validate_index_params(&params).is_ok());
    }

    #[test]
    fn lone_vector_field_composite_index_is_valid() {
        let index = FirestoreCompositeIndex::new(vec![field(
            "embedding",
            FirestoreIndexFieldMode::Vector(FirestoreVectorIndexConfig::new(8)),
        )]);
        assert!(validate_composite_indexes(&[index]).is_ok());
    }

    #[test]
    fn lone_vector_field_dimension_is_still_validated() {
        let index = FirestoreCompositeIndex::new(vec![field(
            "embedding",
            FirestoreIndexFieldMode::Vector(FirestoreVectorIndexConfig::new(0)),
        )]);
        let err = validate_composite_indexes(&[index]).unwrap_err();
        assert!(err.to_string().contains("between 1 and 2048"));
    }

    #[test]
    fn composite_index_with_empty_field_path_is_rejected() {
        let index = FirestoreCompositeIndex::new(vec![asc(""), asc("b")]);
        let err = validate_composite_indexes(&[index]).unwrap_err();
        assert!(err.to_string().contains("empty path"));
    }

    #[test]
    fn composite_index_exceeding_max_declared_fields_is_rejected() {
        let fields: Vec<_> = (0..100).map(|i| asc(&format!("f{i}"))).collect();
        let index = FirestoreCompositeIndex::new(fields);
        let err = validate_composite_indexes(&[index]).unwrap_err();
        assert!(err.to_string().contains("at most 99"));
    }

    #[test]
    fn composite_index_at_max_declared_fields_is_valid() {
        let fields: Vec<_> = (0..99).map(|i| asc(&format!("f{i}"))).collect();
        let index = FirestoreCompositeIndex::new(fields);
        assert!(validate_composite_indexes(&[index]).is_ok());
    }

    #[test]
    fn duplicate_composite_index_after_name_normalisation_is_rejected() {
        let index_a = FirestoreCompositeIndex::new(vec![asc("a"), asc("b")]);
        let index_b =
            FirestoreCompositeIndex::new(vec![asc("a"), asc("b"), asc(IMPLIED_NAME_FIELD)]);
        let err = validate_composite_indexes(&[index_a, index_b]).unwrap_err();
        assert!(err.to_string().contains("index 1 duplicates index 0"));
    }

    #[test]
    fn composite_index_with_name_field_mid_position_is_not_a_duplicate() {
        // Firestore never places an implicit `__name__` mid-index, so a declaration that states
        // it there explicitly is a different index from one that omits `__name__` altogether,
        // not a duplicate of it.
        let index_a = FirestoreCompositeIndex::new(vec![asc("a"), asc("b")]);
        let index_b =
            FirestoreCompositeIndex::new(vec![asc("a"), asc(IMPLIED_NAME_FIELD), asc("b")]);
        assert!(validate_composite_indexes(&[index_a, index_b]).is_ok());
    }

    #[test]
    fn field_override_with_duplicate_index_entries_is_rejected() {
        let overrides = vec![FirestoreFieldOverride {
            target: FirestoreFieldOverrideTarget::Field("tags".to_string()),
            indexes: vec![
                FirestoreFieldOverrideIndex::new(FirestoreIndexFieldMode::ArrayContains),
                FirestoreFieldOverrideIndex::new(FirestoreIndexFieldMode::ArrayContains),
            ],
        }];
        let err = validate_field_overrides(&overrides).unwrap_err();
        assert!(err.to_string().contains("more than once"));
    }

    #[test]
    fn field_override_with_vector_mode_is_rejected() {
        let overrides = vec![FirestoreFieldOverride {
            target: FirestoreFieldOverrideTarget::Field("embedding".to_string()),
            indexes: vec![FirestoreFieldOverrideIndex::new(
                FirestoreIndexFieldMode::Vector(FirestoreVectorIndexConfig::new(8)),
            )],
        }];
        let err = validate_field_overrides(&overrides).unwrap_err();
        assert!(err.to_string().contains("vector index"));
    }

    #[test]
    fn field_override_with_empty_path_is_rejected() {
        let overrides = vec![FirestoreFieldOverride {
            target: FirestoreFieldOverrideTarget::Field(String::new()),
            indexes: vec![],
        }];
        let err = validate_field_overrides(&overrides).unwrap_err();
        assert!(err.to_string().contains("must not be empty"));
    }

    #[test]
    fn field_named_star_is_rejected_pointing_at_all_fields() {
        let overrides = vec![FirestoreFieldOverride {
            target: FirestoreFieldOverrideTarget::Field(ALL_FIELDS_PATH.to_string()),
            indexes: vec![],
        }];
        let err = validate_field_overrides(&overrides).unwrap_err();
        assert!(err.to_string().contains("all_fields()"));
    }

    #[test]
    fn all_fields_target_is_accepted() {
        let overrides = vec![FirestoreFieldOverride {
            target: FirestoreFieldOverrideTarget::AllFields,
            indexes: vec![],
        }];
        assert!(validate_field_overrides(&overrides).is_ok());
    }

    #[test]
    fn all_fields_declared_twice_is_rejected_as_a_duplicate() {
        let overrides = vec![
            FirestoreFieldOverride {
                target: FirestoreFieldOverrideTarget::AllFields,
                indexes: vec![],
            },
            FirestoreFieldOverride {
                target: FirestoreFieldOverrideTarget::AllFields,
                indexes: vec![FirestoreFieldOverrideIndex::new(
                    FirestoreIndexFieldMode::ArrayContains,
                )],
            },
        ];
        let err = validate_field_overrides(&overrides).unwrap_err();
        assert!(err.to_string().contains("declared more than once"));
    }

    #[test]
    fn all_fields_and_a_named_field_are_both_accepted() {
        let overrides = vec![
            FirestoreFieldOverride {
                target: FirestoreFieldOverrideTarget::AllFields,
                indexes: vec![],
            },
            FirestoreFieldOverride {
                target: FirestoreFieldOverrideTarget::Field("country".to_string()),
                indexes: vec![FirestoreFieldOverrideIndex::new(
                    FirestoreIndexFieldMode::Order(FirestoreQueryDirection::Ascending),
                )],
            },
        ];
        assert!(validate_field_overrides(&overrides).is_ok());
    }

    #[test]
    fn single_ttl_field_is_valid() {
        assert!(validate_ttl_fields(&["expires_at".to_string()]).is_ok());
    }

    #[test]
    fn more_than_one_ttl_field_is_rejected() {
        let err = validate_ttl_fields(&["a".to_string(), "b".to_string()]).unwrap_err();
        assert!(err.to_string().contains("at most one TTL field"));
    }

    #[test]
    fn duplicate_ttl_field_is_rejected() {
        let err =
            validate_ttl_fields(&["expires_at".to_string(), "expires_at".to_string()]).unwrap_err();
        assert!(err.to_string().contains("at most one TTL field"));
    }

    #[test]
    fn empty_ttl_field_path_is_rejected() {
        let err = validate_ttl_fields(&[String::new()]).unwrap_err();
        assert!(err.to_string().contains("must not be empty"));
    }
}