arcgis 0.1.3

Type-safe Rust SDK for the ArcGIS REST API with compile-time guarantees
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
//! Types for Feature Service operations.

use crate::{
    ArcGISGeometry, GeometryType, ObjectId, RelationshipCardinality, RelationshipRole, SpatialRel,
};
use derive_setters::Setters;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Serialization helpers for URL query parameters.
mod serde_helpers {
    use crate::ArcGISGeometry;
    use serde::Serializer;

    /// Serializes a Vec<String> as a comma-separated string for URL query parameters.
    pub fn serialize_string_vec<S>(
        vec: &Option<Vec<String>>,
        serializer: S,
    ) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match vec {
            Some(v) => serializer.serialize_str(&v.join(",")),
            None => serializer.serialize_none(),
        }
    }

    /// Serializes a Vec<ObjectId> as a comma-separated string for URL query parameters.
    pub fn serialize_object_ids<S>(
        vec: &Option<Vec<crate::ObjectId>>,
        serializer: S,
    ) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match vec {
            Some(v) => {
                let ids: Vec<String> = v.iter().map(|id| id.to_string()).collect();
                serializer.serialize_str(&ids.join(","))
            }
            None => serializer.serialize_none(),
        }
    }

    /// Serializes geometry as a JSON string for URL query parameters.
    pub fn serialize_geometry<S>(
        geom: &Option<ArcGISGeometry>,
        serializer: S,
    ) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match geom {
            Some(g) => {
                let json = serde_json::to_string(g).map_err(serde::ser::Error::custom)?;
                serializer.serialize_str(&json)
            }
            None => serializer.serialize_none(),
        }
    }

    /// Serializes Vec<StatisticDefinition> as a JSON string for URL query parameters.
    pub fn serialize_statistics<S>(
        stats: &Option<Vec<super::StatisticDefinition>>,
        serializer: S,
    ) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match stats {
            Some(s) => {
                let json = serde_json::to_string(s).map_err(serde::ser::Error::custom)?;
                serializer.serialize_str(&json)
            }
            None => serializer.serialize_none(),
        }
    }

    /// Serializes TopFilter as a JSON string for URL query parameters.
    pub fn serialize_top_filter<S>(
        filter: &Option<super::TopFilter>,
        serializer: S,
    ) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match filter {
            Some(f) => {
                let json = serde_json::to_string(f).map_err(serde::ser::Error::custom)?;
                serializer.serialize_str(&json)
            }
            None => serializer.serialize_none(),
        }
    }
}

/// Response format for feature service queries.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum ResponseFormat {
    /// JSON format.
    #[default]
    Json,
    /// GeoJSON format.
    #[serde(rename = "geojson")]
    GeoJson,
    /// Protocol Buffer format.
    Pbf,
}

/// A single feature returned from a feature service.
#[derive(
    Debug, Clone, PartialEq, Serialize, Deserialize, derive_getters::Getters, derive_new::new,
)]
pub struct Feature {
    /// Feature attributes as key-value pairs.
    attributes: HashMap<String, serde_json::Value>,

    /// Optional geometry.
    #[serde(skip_serializing_if = "Option::is_none")]
    geometry: Option<ArcGISGeometry>,
}

/// A set of features returned from a query.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, derive_getters::Getters, Default)]
pub struct FeatureSet {
    /// Geometry type of features in this set.
    #[serde(rename = "geometryType", skip_serializing_if = "Option::is_none")]
    geometry_type: Option<GeometryType>,

    /// Array of features.
    /// This field is optional because count-only queries don't return features.
    #[serde(default)]
    features: Vec<Feature>,

    /// Count of features (present when returnCountOnly=true).
    #[serde(skip_serializing_if = "Option::is_none")]
    count: Option<u32>,

    /// Whether the result set exceeded the transfer limit.
    #[serde(rename = "exceededTransferLimit", default)]
    exceeded_transfer_limit: bool,
}

impl FeatureSet {
    /// Creates a new FeatureSet.
    pub(crate) fn new(
        geometry_type: Option<GeometryType>,
        features: Vec<Feature>,
        count: Option<u32>,
        exceeded_transfer_limit: bool,
    ) -> Self {
        Self {
            geometry_type,
            features,
            count,
            exceeded_transfer_limit,
        }
    }

    /// Extracts features from the set, consuming it.
    pub fn into_features(self) -> Vec<Feature> {
        self.features
    }

    /// Returns a mutable reference to the features vector (for internal use).
    pub(crate) fn features_mut(&mut self) -> &mut Vec<Feature> {
        &mut self.features
    }
}

/// Parameters for querying features from a feature service.
///
/// Use the builder pattern to construct query parameters.
///
/// # Example
/// ```no_run
/// use arcgis::FeatureQueryParams;
///
/// let params = FeatureQueryParams::builder()
///     .where_clause("POPULATION > 100000")
///     .out_fields(vec!["NAME".to_string(), "POPULATION".to_string()])
///     .return_geometry(true)
///     .build();
/// ```
#[derive(Debug, Clone, Serialize, derive_builder::Builder, derive_getters::Getters, Setters)]
#[builder(setter(into, strip_option), default)]
#[setters(prefix = "set_", borrow_self)]
pub struct FeatureQueryParams {
    /// WHERE clause for the query.
    #[serde(rename = "where")]
    #[builder(default = "String::from(\"1=1\")")]
    where_clause: String,

    /// Fields to include in the response.
    /// If None, all fields are returned.
    #[serde(
        rename = "outFields",
        skip_serializing_if = "Option::is_none",
        serialize_with = "serde_helpers::serialize_string_vec"
    )]
    out_fields: Option<Vec<String>>,

    /// Whether to return geometry with features.
    #[serde(rename = "returnGeometry")]
    #[builder(default = "true")]
    return_geometry: bool,

    /// Response format.
    #[serde(rename = "f")]
    #[builder(default)]
    format: ResponseFormat,

    /// Geometry to use for spatial filter.
    #[serde(
        skip_serializing_if = "Option::is_none",
        serialize_with = "serde_helpers::serialize_geometry"
    )]
    geometry: Option<ArcGISGeometry>,

    /// Geometry type of the geometry parameter.
    #[serde(rename = "geometryType", skip_serializing_if = "Option::is_none")]
    geometry_type: Option<GeometryType>,

    /// Spatial relationship to use for spatial filter.
    #[serde(rename = "spatialRel", skip_serializing_if = "Option::is_none")]
    spatial_rel: Option<SpatialRel>,

    /// Maximum number of features to return.
    #[serde(rename = "resultRecordCount", skip_serializing_if = "Option::is_none")]
    result_record_count: Option<u32>,

    /// Offset for pagination.
    #[serde(rename = "resultOffset", skip_serializing_if = "Option::is_none")]
    result_offset: Option<u32>,

    /// Object IDs to query.
    #[serde(
        rename = "objectIds",
        skip_serializing_if = "Option::is_none",
        serialize_with = "serde_helpers::serialize_object_ids"
    )]
    object_ids: Option<Vec<ObjectId>>,

    /// Whether to return distinct values only.
    #[serde(
        rename = "returnDistinctValues",
        skip_serializing_if = "Option::is_none"
    )]
    return_distinct_values: Option<bool>,

    /// Whether to return object IDs only.
    #[serde(rename = "returnIdsOnly", skip_serializing_if = "Option::is_none")]
    return_ids_only: Option<bool>,

    /// Whether to return count only.
    #[serde(rename = "returnCountOnly", skip_serializing_if = "Option::is_none")]
    return_count_only: Option<bool>,

    /// ORDER BY clause.
    #[serde(
        rename = "orderByFields",
        skip_serializing_if = "Option::is_none",
        serialize_with = "serde_helpers::serialize_string_vec"
    )]
    order_by_fields: Option<Vec<String>>,

    /// GROUP BY clause.
    #[serde(
        rename = "groupByFieldsForStatistics",
        skip_serializing_if = "Option::is_none",
        serialize_with = "serde_helpers::serialize_string_vec"
    )]
    group_by_fields: Option<Vec<String>>,

    /// Statistics to calculate (aggregate queries).
    ///
    /// When specified, only these query parameters can be used:
    /// groupByFieldsForStatistics, orderByFields, time, returnDistinctValues, where.
    #[serde(
        rename = "outStatistics",
        skip_serializing_if = "Option::is_none",
        serialize_with = "serde_helpers::serialize_statistics"
    )]
    out_statistics: Option<Vec<StatisticDefinition>>,

    /// HAVING clause for filtering aggregated results.
    ///
    /// Only valid when `out_statistics` is specified.
    /// Example: `"COUNT(*) > 1000"` or `"SUM(AREA) > 5000"`
    #[serde(rename = "having", skip_serializing_if = "Option::is_none")]
    having: Option<String>,

    /// Output spatial reference WKID.
    #[serde(rename = "outSR", skip_serializing_if = "Option::is_none")]
    out_sr: Option<i32>,
}

impl Default for FeatureQueryParams {
    fn default() -> Self {
        Self {
            where_clause: "1=1".to_string(),
            out_fields: None,
            return_geometry: true,
            format: ResponseFormat::default(),
            geometry: None,
            geometry_type: None,
            spatial_rel: None,
            result_record_count: None,
            result_offset: None,
            object_ids: None,
            return_distinct_values: None,
            return_ids_only: None,
            return_count_only: None,
            order_by_fields: None,
            group_by_fields: None,
            out_statistics: None,
            having: None,
            out_sr: None,
        }
    }
}

impl FeatureQueryParams {
    /// Creates a new builder for FeatureQueryParams.
    pub fn builder() -> FeatureQueryParamsBuilder {
        FeatureQueryParamsBuilder::default()
    }
}

/// Statistical operation type for aggregate queries.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum StatisticType {
    /// Count of records
    Count,
    /// Sum of field values
    Sum,
    /// Minimum value
    Min,
    /// Maximum value
    Max,
    /// Average (mean) value
    Avg,
    /// Standard deviation
    Stddev,
    /// Variance
    Var,
    /// Continuous percentile
    #[serde(rename = "PERCENTILE_CONT")]
    PercentileCont,
    /// Discrete percentile
    #[serde(rename = "PERCENTILE_DISC")]
    PercentileDisc,
}

/// Defines a field-based statistic to calculate.
///
/// Used with [`FeatureQueryParams::out_statistics`] to perform aggregate queries.
///
/// # Example
///
/// ```
/// use arcgis::{StatisticDefinition, StatisticType};
///
/// let stat = StatisticDefinition::new(
///     StatisticType::Avg,
///     "POPULATION".to_string(),
///     "avg_population".to_string()
/// );
/// ```
#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    Hash,
    Serialize,
    Deserialize,
    derive_getters::Getters,
    derive_new::new,
)]
#[serde(rename_all = "camelCase")]
pub struct StatisticDefinition {
    /// The type of statistic to calculate.
    statistic_type: StatisticType,

    /// The field name to calculate statistics on.
    on_statistic_field: String,

    /// The output field name for the result.
    out_statistic_field_name: String,
}

/// Response from a feature statistics query.
///
/// Contains aggregate results when querying with `outStatistics`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, derive_getters::Getters)]
#[serde(rename_all = "camelCase")]
pub struct FeatureStatisticsResponse {
    /// The features containing statistical results.
    features: Vec<Feature>,

    /// Field aliases mapping output field names to descriptions.
    #[serde(default)]
    field_aliases: HashMap<String, String>,
}

/// Parameters for querying related records.
///
/// Use [`RelatedRecordsParams::builder()`] to construct instances.
///
/// # Example
///
/// ```
/// use arcgis::{RelatedRecordsParams, ObjectId};
///
/// let params = RelatedRecordsParams::builder()
///     .object_ids(vec![ObjectId::new(1), ObjectId::new(2)])
///     .relationship_id(3u32)
///     .out_fields(vec!["NAME".to_string(), "STATUS".to_string()])
///     .build()
///     .expect("Valid params");
/// ```
#[derive(Debug, Clone, Serialize, derive_builder::Builder, derive_getters::Getters)]
#[builder(setter(into, strip_option), default)]
pub struct RelatedRecordsParams {
    /// Object IDs of features to query related records for (REQUIRED).
    #[serde(
        rename = "objectIds",
        serialize_with = "serde_helpers::serialize_object_ids"
    )]
    object_ids: Option<Vec<ObjectId>>,

    /// ID of the relationship to query (REQUIRED).
    #[serde(rename = "relationshipId")]
    relationship_id: Option<u32>,

    /// Fields to include in the response.
    #[serde(
        rename = "outFields",
        skip_serializing_if = "Option::is_none",
        serialize_with = "serde_helpers::serialize_string_vec"
    )]
    out_fields: Option<Vec<String>>,

    /// WHERE clause to filter related records.
    #[serde(
        rename = "definitionExpression",
        skip_serializing_if = "Option::is_none"
    )]
    definition_expression: Option<String>,

    /// Whether to return geometry with features.
    #[serde(rename = "returnGeometry", skip_serializing_if = "Option::is_none")]
    return_geometry: Option<bool>,

    /// Output spatial reference WKID.
    #[serde(rename = "outSR", skip_serializing_if = "Option::is_none")]
    out_sr: Option<i32>,

    /// Maximum offset for geometry generalization.
    #[serde(rename = "maxAllowableOffset", skip_serializing_if = "Option::is_none")]
    max_allowable_offset: Option<f64>,

    /// Decimal places for geometry coordinates.
    #[serde(rename = "geometryPrecision", skip_serializing_if = "Option::is_none")]
    geometry_precision: Option<i32>,

    /// Return z-values.
    #[serde(rename = "returnZ", skip_serializing_if = "Option::is_none")]
    return_z: Option<bool>,

    /// Return m-values.
    #[serde(rename = "returnM", skip_serializing_if = "Option::is_none")]
    return_m: Option<bool>,

    /// Geodatabase version.
    #[serde(rename = "gdbVersion", skip_serializing_if = "Option::is_none")]
    gdb_version: Option<String>,

    /// Historic moment (epoch milliseconds).
    #[serde(rename = "historicMoment", skip_serializing_if = "Option::is_none")]
    historic_moment: Option<i64>,

    /// Return only counts per object ID.
    #[serde(rename = "returnCountOnly", skip_serializing_if = "Option::is_none")]
    return_count_only: Option<bool>,

    /// ORDER BY clause.
    #[serde(
        rename = "orderByFields",
        skip_serializing_if = "Option::is_none",
        serialize_with = "serde_helpers::serialize_string_vec"
    )]
    order_by_fields: Option<Vec<String>>,

    /// Offset for pagination.
    #[serde(rename = "resultOffset", skip_serializing_if = "Option::is_none")]
    result_offset: Option<u32>,

    /// Maximum number of features to return per object ID.
    #[serde(rename = "resultRecordCount", skip_serializing_if = "Option::is_none")]
    result_record_count: Option<u32>,

    /// Response format.
    #[serde(rename = "f")]
    #[builder(default = "ResponseFormat::Json")]
    format: ResponseFormat,
}

impl Default for RelatedRecordsParams {
    fn default() -> Self {
        Self {
            object_ids: None,
            relationship_id: None,
            out_fields: None,
            definition_expression: None,
            return_geometry: Some(true),
            out_sr: None,
            max_allowable_offset: None,
            geometry_precision: None,
            return_z: None,
            return_m: None,
            gdb_version: None,
            historic_moment: None,
            return_count_only: None,
            order_by_fields: None,
            result_offset: None,
            result_record_count: None,
            format: ResponseFormat::Json,
        }
    }
}

impl RelatedRecordsParams {
    /// Creates a builder for RelatedRecordsParams.
    pub fn builder() -> RelatedRecordsParamsBuilder {
        RelatedRecordsParamsBuilder::default()
    }
}

/// A group of related records for a specific source object ID.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, derive_getters::Getters)]
#[serde(rename_all = "camelCase")]
pub struct RelatedRecordGroup {
    /// The source object ID.
    object_id: ObjectId,

    /// Related records for this object ID.
    #[serde(default)]
    related_records: Vec<Feature>,
}

/// Response from a query related records operation.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, derive_getters::Getters)]
#[serde(rename_all = "camelCase")]
pub struct RelatedRecordsResponse {
    /// Groups of related records, one per source object ID.
    #[serde(default)]
    related_record_groups: Vec<RelatedRecordGroup>,

    /// Geometry type of the related records (if applicable).
    #[serde(skip_serializing_if = "Option::is_none")]
    geometry_type: Option<GeometryType>,

    /// Spatial reference of the geometries.
    #[serde(skip_serializing_if = "Option::is_none")]
    spatial_reference: Option<serde_json::Value>,

    /// Field definitions.
    #[serde(default)]
    fields: Vec<serde_json::Value>,
}

/// Top filter specification for queryTopFeatures operations.
///
/// Specifies how to group results, how many features to return from each group,
/// and how to order results within each group.
///
/// # Example
///
/// ```
/// use arcgis::TopFilter;
///
/// // Get top 3 most populous cities from each state
/// let filter = TopFilter::new(
///     vec!["State".to_string()],
///     3,
///     vec!["Population DESC".to_string()],
/// );
/// ```
#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    Hash,
    Serialize,
    Deserialize,
    derive_getters::Getters,
    derive_new::new,
)]
#[serde(rename_all = "camelCase")]
pub struct TopFilter {
    /// Fields to group results by.
    group_by_fields: Vec<String>,

    /// Number of top features to return from each group.
    top_count: u32,

    /// Fields to order results by (format: "FieldName ASC" or "FieldName DESC").
    order_by_fields: Vec<String>,
}

/// Parameters for querying top features from a feature service layer.
///
/// The queryTopFeatures operation returns features based on ranking within groups.
/// For example, you can query the top 3 most populous cities from each state.
///
/// # Example
///
/// ```
/// use arcgis::{TopFeaturesParams, TopFilter};
///
/// let filter = TopFilter::new(
///     vec!["State".to_string()],
///     3,
///     vec!["Population DESC".to_string()],
/// );
///
/// let params = TopFeaturesParams::builder()
///     .top_filter(filter)
///     .where_("Population > 100000")
///     .out_fields(vec!["Name".to_string(), "Population".to_string()])
///     .build()
///     .expect("Valid params");
/// ```
#[derive(Debug, Clone, Serialize, derive_builder::Builder, derive_getters::Getters)]
#[builder(setter(into, strip_option), default)]
pub struct TopFeaturesParams {
    /// Required: Top filter specification (group by, count, order by).
    #[serde(
        rename = "topFilter",
        serialize_with = "serde_helpers::serialize_top_filter"
    )]
    top_filter: Option<TopFilter>,

    /// WHERE clause for the query filter.
    #[serde(skip_serializing_if = "Option::is_none")]
    where_: Option<String>,

    /// Object IDs to query.
    #[serde(
        rename = "objectIds",
        skip_serializing_if = "Option::is_none",
        serialize_with = "serde_helpers::serialize_object_ids"
    )]
    object_ids: Option<Vec<ObjectId>>,

    /// Time instant or extent to query.
    #[serde(skip_serializing_if = "Option::is_none")]
    time: Option<String>,

    /// Geometry to apply as spatial filter.
    #[serde(
        skip_serializing_if = "Option::is_none",
        serialize_with = "serde_helpers::serialize_geometry"
    )]
    geometry: Option<ArcGISGeometry>,

    /// Type of geometry being used as spatial filter.
    #[serde(rename = "geometryType", skip_serializing_if = "Option::is_none")]
    geometry_type: Option<GeometryType>,

    /// Spatial reference of input geometry.
    #[serde(rename = "inSR", skip_serializing_if = "Option::is_none")]
    in_sr: Option<i32>,

    /// Spatial relationship for the query.
    #[serde(rename = "spatialRel", skip_serializing_if = "Option::is_none")]
    spatial_rel: Option<SpatialRel>,

    /// Buffer distance for input geometries.
    #[serde(skip_serializing_if = "Option::is_none")]
    distance: Option<f64>,

    /// Units for distance parameter.
    #[serde(skip_serializing_if = "Option::is_none")]
    units: Option<String>,

    /// Fields to include in the response.
    #[serde(
        rename = "outFields",
        skip_serializing_if = "Option::is_none",
        serialize_with = "serde_helpers::serialize_string_vec"
    )]
    out_fields: Option<Vec<String>>,

    /// Whether to return geometry with the results (default: true).
    #[serde(rename = "returnGeometry", skip_serializing_if = "Option::is_none")]
    return_geometry: Option<bool>,

    /// Maximum offset for geometry generalization.
    #[serde(rename = "maxAllowableOffset", skip_serializing_if = "Option::is_none")]
    max_allowable_offset: Option<f64>,

    /// Number of decimal places for returned geometries.
    #[serde(rename = "geometryPrecision", skip_serializing_if = "Option::is_none")]
    geometry_precision: Option<i32>,

    /// Spatial reference for returned geometry.
    #[serde(rename = "outSR", skip_serializing_if = "Option::is_none")]
    out_sr: Option<i32>,

    /// Whether to return only object IDs.
    #[serde(rename = "returnIdsOnly", skip_serializing_if = "Option::is_none")]
    return_ids_only: Option<bool>,

    /// Whether to return only the feature count.
    #[serde(rename = "returnCountOnly", skip_serializing_if = "Option::is_none")]
    return_count_only: Option<bool>,

    /// Whether to return only the extent.
    #[serde(rename = "returnExtentOnly", skip_serializing_if = "Option::is_none")]
    return_extent_only: Option<bool>,

    /// Whether to include z-values if available.
    #[serde(rename = "returnZ", skip_serializing_if = "Option::is_none")]
    return_z: Option<bool>,

    /// Whether to include m-values if available.
    #[serde(rename = "returnM", skip_serializing_if = "Option::is_none")]
    return_m: Option<bool>,

    /// Control on the number of features returned.
    #[serde(rename = "resultType", skip_serializing_if = "Option::is_none")]
    result_type: Option<String>,

    /// Output format (json, geojson, pbf).
    #[serde(skip_serializing_if = "Option::is_none")]
    f: Option<String>,
}

impl Default for TopFeaturesParams {
    fn default() -> Self {
        Self {
            top_filter: None,
            where_: None,
            object_ids: None,
            time: None,
            geometry: None,
            geometry_type: None,
            in_sr: None,
            spatial_rel: None,
            distance: None,
            units: None,
            out_fields: None,
            return_geometry: Some(true),
            max_allowable_offset: None,
            geometry_precision: None,
            out_sr: None,
            return_ids_only: None,
            return_count_only: None,
            return_extent_only: None,
            return_z: None,
            return_m: None,
            result_type: None,
            f: Some("json".to_string()),
        }
    }
}

impl TopFeaturesParams {
    /// Creates a builder for TopFeaturesParams.
    pub fn builder() -> TopFeaturesParamsBuilder {
        TopFeaturesParamsBuilder::default()
    }
}

/// Response from truncate operation.
///
/// Indicates whether the truncate operation completed successfully.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, derive_getters::Getters)]
pub struct TruncateResult {
    /// Whether the operation succeeded.
    success: bool,
}

/// Response from queryDomains operation.
///
/// Contains domain and subtype information for requested layers.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, derive_getters::Getters)]
pub struct QueryDomainsResponse {
    /// Array of layer domain information.
    layers: Vec<LayerDomainInfo>,
}

/// Domain information for a single layer.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, derive_getters::Getters)]
#[serde(rename_all = "camelCase")]
pub struct LayerDomainInfo {
    /// Layer ID.
    id: i32,

    /// Layer name.
    #[serde(skip_serializing_if = "Option::is_none")]
    name: Option<String>,

    /// Field domains.
    #[serde(default)]
    domains: HashMap<String, Domain>,

    /// Subtypes.
    #[serde(skip_serializing_if = "Option::is_none")]
    subtypes: Option<Vec<Subtype>>,
}

/// A coded value domain.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, derive_getters::Getters)]
#[serde(rename_all = "camelCase")]
pub struct Domain {
    /// Domain type (usually "codedValue" or "range").
    #[serde(rename = "type")]
    domain_type: String,

    /// Domain name.
    name: String,

    /// Coded values (for coded value domains).
    #[serde(skip_serializing_if = "Option::is_none")]
    coded_values: Option<Vec<CodedValue>>,

    /// Range (for range domains).
    #[serde(skip_serializing_if = "Option::is_none")]
    range: Option<Vec<serde_json::Value>>,
}

/// A coded value in a domain.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, derive_getters::Getters)]
pub struct CodedValue {
    /// The coded value.
    code: serde_json::Value,

    /// The human-readable name.
    name: String,
}

/// Subtype information.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, derive_getters::Getters)]
#[serde(rename_all = "camelCase")]
pub struct Subtype {
    /// Subtype code.
    code: i32,

    /// Subtype name.
    name: String,

    /// Default values for fields.
    #[serde(skip_serializing_if = "Option::is_none")]
    default_values: Option<HashMap<String, serde_json::Value>>,

    /// Field domains for this subtype.
    #[serde(skip_serializing_if = "Option::is_none")]
    domains: Option<HashMap<String, Domain>>,
}

/// Field calculation expression for calculateRecords operation.
///
/// Defines a field and either a scalar value or SQL expression to calculate its value.
/// Either `value` or `sql_expression` must be provided, but not both.
///
/// # Example
///
/// ```rust
/// use arcgis::FieldCalculation;
/// use serde_json::json;
///
/// // Using a scalar value
/// let calc1 = FieldCalculation::with_value("Quality", json!(3));
///
/// // Using a SQL expression
/// let calc2 = FieldCalculation::with_sql_expression("Area", "SHAPE_AREA * 0.0001");
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FieldCalculation {
    /// Name of the field to update.
    field: String,

    /// Scalar value to assign to the field.
    ///
    /// Mutually exclusive with `sql_expression`.
    #[serde(skip_serializing_if = "Option::is_none")]
    value: Option<serde_json::Value>,

    /// SQL expression to calculate the field value.
    ///
    /// Mutually exclusive with `value`.
    #[serde(rename = "sqlExpression", skip_serializing_if = "Option::is_none")]
    sql_expression: Option<String>,
}

impl FieldCalculation {
    /// Creates a field calculation with a scalar value.
    pub fn with_value(field: impl Into<String>, value: serde_json::Value) -> Self {
        Self {
            field: field.into(),
            value: Some(value),
            sql_expression: None,
        }
    }

    /// Creates a field calculation with a SQL expression.
    pub fn with_sql_expression(
        field: impl Into<String>,
        sql_expression: impl Into<String>,
    ) -> Self {
        Self {
            field: field.into(),
            value: None,
            sql_expression: Some(sql_expression.into()),
        }
    }

    /// Returns the field name.
    pub fn field(&self) -> &str {
        &self.field
    }

    /// Returns the scalar value, if set.
    pub fn value(&self) -> Option<&serde_json::Value> {
        self.value.as_ref()
    }

    /// Returns the SQL expression, if set.
    pub fn sql_expression(&self) -> Option<&str> {
        self.sql_expression.as_deref()
    }
}

// ==================== Relationship Classes ====================

/// Cardinality constraint rule for a relationship class.
///
/// # ESRI Documentation
///
/// Source: <https://developers.arcgis.com/rest/services-reference/enterprise/relationships-feature-service/>
///
/// Rules define minimum and maximum cardinality constraints for subtypes
/// on each side of the relationship.
///
/// # Example from ESRI
///
/// ```json
/// {
///   "ruleID": 1,
///   "originSubtypeCode": 0,
///   "originMinimumCardinality": 0,
///   "originMaximumCardinality": -1,
///   "destinationSubtypeCode": 0,
///   "destinationMinimumCardinality": 0,
///   "destinationMaximumCardinality": -1
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, derive_getters::Getters)]
#[serde(rename_all = "camelCase")]
pub struct RelationshipRule {
    /// Rule identifier.
    ///
    /// Note: ESRI uses `ruleID` (not camelCase) for this field.
    #[serde(rename = "ruleID")]
    rule_id: i32,

    /// Subtype code on the origin side (0 = all subtypes).
    origin_subtype_code: i32,

    /// Minimum cardinality on origin side (0 = no minimum).
    origin_minimum_cardinality: i32,

    /// Maximum cardinality on origin side (-1 = unlimited).
    origin_maximum_cardinality: i32,

    /// Subtype code on destination side (0 = all subtypes).
    destination_subtype_code: i32,

    /// Minimum cardinality on destination side (0 = no minimum).
    destination_minimum_cardinality: i32,

    /// Maximum cardinality on destination side (-1 = unlimited).
    destination_maximum_cardinality: i32,
}

/// Full relationship class definition from the relationships resource.
///
/// # ESRI Documentation
///
/// Source: <https://developers.arcgis.com/rest/services-reference/enterprise/relationships-feature-service/>
///
/// Obtained via `GET /FeatureServer/relationships` or `GET /FeatureServer/{layerId}/relationships`.
/// Contains the complete definition of a relationship class including keys, cardinality,
/// and optional cardinality rules.
///
/// # Attributed Relationships
///
/// When `attributed` is `true`, the relationship class has additional fields
/// stored in a separate relationship table, indicated by `relationship_table_id`
/// and `key_field_in_relationship_table`.
///
/// # Example from ESRI
///
/// ```json
/// {
///   "id": 2,
///   "name": "Buildings_Permits",
///   "cardinality": "esriRelCardinalityOneToMany",
///   "originLayerId": 0,
///   "originPrimaryKey": "GlobalID",
///   "originForeignKey": "BuildingGUID",
///   "destinationLayerId": 1,
///   "role": "esriRelRoleOrigin",
///   "attributed": false,
///   "catalogID": "{SOME-GUID}",
///   "rules": []
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, derive_getters::Getters)]
#[serde(rename_all = "camelCase")]
pub struct RelationshipClass {
    /// Relationship class identifier.
    id: i32,

    /// Relationship class name.
    #[serde(skip_serializing_if = "Option::is_none")]
    name: Option<String>,

    /// Cardinality of the relationship.
    cardinality: RelationshipCardinality,

    /// ID of the origin layer or table.
    origin_layer_id: i32,

    /// Primary key field on the origin layer.
    origin_primary_key: String,

    /// Foreign key field on the origin layer (for one-to-many).
    #[serde(skip_serializing_if = "Option::is_none")]
    origin_foreign_key: Option<String>,

    /// ID of the destination layer or table.
    #[serde(skip_serializing_if = "Option::is_none")]
    destination_layer_id: Option<i32>,

    /// Primary key field on the destination layer.
    #[serde(skip_serializing_if = "Option::is_none")]
    destination_primary_key: Option<String>,

    /// Foreign key field on the destination layer.
    #[serde(skip_serializing_if = "Option::is_none")]
    destination_foreign_key: Option<String>,

    /// Label for traversing from destination to origin.
    #[serde(skip_serializing_if = "Option::is_none")]
    backward_path_label: Option<String>,

    /// Label for traversing from origin to destination.
    #[serde(skip_serializing_if = "Option::is_none")]
    forward_path_label: Option<String>,

    /// Role of the origin layer in this relationship.
    role: RelationshipRole,

    /// Whether the relationship has attribute fields.
    ///
    /// When `true`, additional attributes are stored in `relationship_table_id`.
    attributed: bool,

    /// ID of the relationship table (for attributed relationships).
    #[serde(skip_serializing_if = "Option::is_none")]
    relationship_table_id: Option<i32>,

    /// Key field in the relationship table (for attributed relationships).
    #[serde(skip_serializing_if = "Option::is_none")]
    key_field_in_relationship_table: Option<String>,

    /// Catalog GUID for the relationship class.
    ///
    /// Note: ESRI uses `catalogID` (not camelCase) for this field.
    #[serde(rename = "catalogID", skip_serializing_if = "Option::is_none")]
    catalog_id: Option<String>,

    /// Cardinality constraint rules.
    #[serde(default)]
    rules: Vec<RelationshipRule>,
}

/// Response from the relationships resource.
///
/// # ESRI Documentation
///
/// Source: <https://developers.arcgis.com/rest/services-reference/enterprise/relationships-feature-service/>
///
/// Returned by `GET /FeatureServer/relationships` which lists all relationship
/// classes across the service.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, derive_getters::Getters)]
pub struct RelationshipsResponse {
    /// All relationship classes defined in the service.
    relationships: Vec<RelationshipClass>,
}