scim-server 0.4.0

A comprehensive SCIM 2.0 server library for Rust with multi-tenant support and type-safe operations
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
//! Test data builders for creating valid and invalid SCIM resources.
//!
//! This module provides fluent builders for creating test data that can be
//! systematically modified to test specific validation errors.

use super::ValidationErrorCode;
use scim_server::resource::value_objects::{ExternalId, ResourceId, SchemaUri, UserName};
use serde_json::{Value, json};

/// Builder for User resources with fluent API for creating test data
#[derive(Debug, Clone)]
pub struct UserBuilder {
    data: Value,
    expected_errors: Vec<ValidationErrorCode>,
}

impl UserBuilder {
    /// Create a new UserBuilder with minimal valid User data
    pub fn new() -> Self {
        Self {
            data: json!({
                "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
                "id": "2819c223-7f76-453a-919d-413861904646",
                "userName": "bjensen@example.com",
                "meta": {
                    "resourceType": "User",
                    "created": "2010-01-23T04:56:22Z",
                    "lastModified": "2011-05-13T04:42:34Z",
                    "version": "W/\"3694e05e9dff590\"",
                    "location": "https://example.com/v2/Users/2819c223-7f76-453a-919d-413861904646"
                }
            }),
            expected_errors: Vec::new(),
        }
    }

    /// Create a UserBuilder with RFC 7643 Section 8.2 full example
    pub fn new_full() -> Self {
        Self {
            data: json!({
                "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
                "id": "2819c223-7f76-453a-919d-413861904646",
                "externalId": "701984",
                "userName": "bjensen@example.com",
                "name": {
                    "formatted": "Ms. Barbara J Jensen, III",
                    "familyName": "Jensen",
                    "givenName": "Barbara",
                    "middleName": "Jane",
                    "honorificPrefix": "Ms.",
                    "honorificSuffix": "III"
                },
                "displayName": "Babs Jensen",
                "emails": [
                    {
                        "value": "bjensen@example.com",
                        "type": "work",
                        "primary": true
                    },
                    {
                        "value": "babs@jensen.org",
                        "type": "home"
                    }
                ],
                "phoneNumbers": [
                    {
                        "value": "555-555-5555",
                        "type": "work"
                    },
                    {
                        "value": "555-555-4444",
                        "type": "mobile"
                    }
                ],
                "active": true,
                "meta": {
                    "resourceType": "User",
                    "created": "2010-01-23T04:56:22Z",
                    "lastModified": "2011-05-13T04:42:34Z",
                    "version": "W/\"a330bc54f0671c9\"",
                    "location": "https://example.com/v2/Users/2819c223-7f76-453a-919d-413861904646"
                }
            }),
            expected_errors: Vec::new(),
        }
    }

    // Schema structure modifications (Errors 1-8)

    /// Remove the schemas attribute - Error #1: Missing required schemas attribute
    pub fn without_schemas(mut self) -> Self {
        self.data.as_object_mut().unwrap().remove("schemas");
        self.expected_errors
            .push(ValidationErrorCode::MissingSchemas);
        self
    }

    /// Set empty schemas array - Error #2: Empty schemas array
    pub fn with_empty_schemas(mut self) -> Self {
        self.data["schemas"] = json!([]);
        self.expected_errors.push(ValidationErrorCode::EmptySchemas);
        self
    }

    /// Set invalid schema URI - Error #3: Invalid schema URI format
    pub fn with_invalid_schema_uri(mut self) -> Self {
        self.data["schemas"] = json!(["not-a-valid-uri"]);
        self.expected_errors
            .push(ValidationErrorCode::InvalidSchemaUri);
        self
    }

    /// Set unknown schema URI - Error #4: Unknown/unregistered schema URI
    pub fn with_unknown_schema_uri(mut self) -> Self {
        self.data["schemas"] = json!(["urn:ietf:params:scim:schemas:core:2.0:UnknownResource"]);
        self.expected_errors
            .push(ValidationErrorCode::UnknownSchemaUri);
        self
    }

    /// Set duplicate schema URIs - Error #5: Duplicate schema URIs
    pub fn with_duplicate_schema_uris(mut self) -> Self {
        self.data["schemas"] = json!([
            "urn:ietf:params:scim:schemas:core:2.0:User",
            "urn:ietf:params:scim:schemas:core:2.0:User"
        ]);
        self.expected_errors
            .push(ValidationErrorCode::DuplicateSchemaUri);
        self
    }

    // Common attribute modifications (Errors 9-21)

    /// Remove the id attribute - Error #9: Missing required id attribute
    pub fn without_id(mut self) -> Self {
        self.data.as_object_mut().unwrap().remove("id");
        self.expected_errors.push(ValidationErrorCode::MissingId);
        self
    }

    /// Set empty id value - Error #10: Empty or null id value
    pub fn with_empty_id(mut self) -> Self {
        self.data["id"] = json!("");
        self.expected_errors.push(ValidationErrorCode::EmptyId);
        self
    }

    /// Set reserved bulkId value - Error #11: Invalid id format (reserved keyword)
    pub fn with_reserved_id(mut self) -> Self {
        self.data["id"] = json!("bulkId");
        self.expected_errors
            .push(ValidationErrorCode::InvalidIdFormat);
        self
    }

    /// Set specific id value - Helper for valid id
    pub fn with_id(mut self, id: &str) -> Self {
        self.data["id"] = json!(id);
        self
    }

    /// Set numeric id value - Error #11: Invalid id format (non-string)
    pub fn with_numeric_id(mut self) -> Self {
        self.data["id"] = json!(123);
        self.expected_errors
            .push(ValidationErrorCode::InvalidIdFormat);
        self
    }

    /// Set array id value - Error #11: Invalid id format (array)
    pub fn with_array_id(mut self) -> Self {
        self.data["id"] = json!(["123", "456"]);
        self.expected_errors
            .push(ValidationErrorCode::InvalidIdFormat);
        self
    }

    /// Set object id value - Error #11: Invalid id format (object)
    pub fn with_object_id(mut self) -> Self {
        self.data["id"] = json!({"nested": "value"});
        self.expected_errors
            .push(ValidationErrorCode::InvalidIdFormat);
        self
    }

    /// Set specific external id value - Helper for valid external id
    pub fn with_external_id(mut self, external_id: &str) -> Self {
        self.data["externalId"] = json!(external_id);
        self
    }

    /// Set numeric external id value - Error #13: Invalid external id format
    pub fn with_numeric_external_id(mut self) -> Self {
        self.data["externalId"] = json!(123);
        self.expected_errors
            .push(ValidationErrorCode::InvalidExternalId);
        self
    }

    /// Set array external id value - Error #13: Invalid external id format
    pub fn with_array_external_id(mut self) -> Self {
        self.data["externalId"] = json!(["ext1", "ext2"]);
        self.expected_errors
            .push(ValidationErrorCode::InvalidExternalId);
        self
    }

    /// Remove userName attribute - Error #22: Missing required attribute
    pub fn without_username(mut self) -> Self {
        self.data.as_object_mut().unwrap().remove("userName");
        self.expected_errors
            .push(ValidationErrorCode::MissingRequiredAttribute);
        self
    }

    /// Set invalid data type for userName - Error #23: Invalid data type
    pub fn with_invalid_username_type(mut self) -> Self {
        self.data["userName"] = json!(123); // Number instead of string
        self.expected_errors
            .push(ValidationErrorCode::InvalidDataType);
        self
    }

    /// Set invalid meta structure - Error #14: Invalid meta structure
    pub fn with_invalid_meta_structure(mut self) -> Self {
        self.data["meta"] = json!("not-an-object");
        self.expected_errors
            .push(ValidationErrorCode::InvalidMetaStructure);
        self
    }

    /// Set string meta value - Error #14: Invalid meta structure
    pub fn with_string_meta(mut self) -> Self {
        self.data["meta"] = json!("string-meta");
        self.expected_errors
            .push(ValidationErrorCode::InvalidMetaStructure);
        self
    }

    /// Set array meta value - Error #14: Invalid meta structure
    pub fn with_array_meta(mut self) -> Self {
        self.data["meta"] = json!(["array", "meta"]);
        self.expected_errors
            .push(ValidationErrorCode::InvalidMetaStructure);
        self
    }

    /// Remove meta.resourceType - Error #15: Missing required meta.resourceType
    pub fn without_meta_resource_type(mut self) -> Self {
        if let Some(meta) = self.data["meta"].as_object_mut() {
            meta.remove("resourceType");
        }
        self.expected_errors
            .push(ValidationErrorCode::MissingResourceType);
        self
    }

    /// Set invalid meta.resourceType - Error #16: Invalid meta.resourceType value
    pub fn with_invalid_meta_resource_type(mut self) -> Self {
        self.data["meta"]["resourceType"] = json!("InvalidType");
        self.expected_errors
            .push(ValidationErrorCode::InvalidResourceType);
        self
    }

    /// Set numeric meta.resourceType - Error #16: Invalid meta.resourceType value
    pub fn with_numeric_meta_resource_type(mut self) -> Self {
        self.data["meta"]["resourceType"] = json!(123);
        self.expected_errors
            .push(ValidationErrorCode::InvalidResourceType);
        self
    }

    /// Add readonly meta attributes - Error #17: Client-provided readonly meta attributes
    pub fn with_readonly_meta_attributes(mut self) -> Self {
        if let Some(meta) = self.data["meta"].as_object_mut() {
            meta.insert("created".to_string(), json!("2024-01-01T00:00:00Z"));
            meta.insert("lastModified".to_string(), json!("2024-01-01T00:00:00Z"));
            meta.insert(
                "location".to_string(),
                json!("https://example.com/Users/123"),
            );
            meta.insert("version".to_string(), json!("W/\"123456\""));
        }
        self.expected_errors
            .push(ValidationErrorCode::ClientProvidedMeta);
        self
    }

    /// Set invalid created datetime - Error #18: Invalid meta.created datetime format
    pub fn with_invalid_created_datetime(mut self) -> Self {
        self.data["meta"]["created"] = json!("invalid-date");
        self.expected_errors
            .push(ValidationErrorCode::InvalidCreatedDateTime);
        self
    }

    /// Set numeric created datetime - Error #18: Invalid meta.created datetime format
    pub fn with_numeric_created_datetime(mut self) -> Self {
        self.data["meta"]["created"] = json!(123456789);
        self.expected_errors
            .push(ValidationErrorCode::InvalidCreatedDateTime);
        self
    }

    /// Set invalid last modified datetime - Error #19: Invalid meta.lastModified datetime format
    pub fn with_invalid_last_modified_datetime(mut self) -> Self {
        self.data["meta"]["lastModified"] = json!("not-a-date");
        self.expected_errors
            .push(ValidationErrorCode::InvalidModifiedDateTime);
        self
    }

    /// Set invalid location URI - Error #20: Invalid meta.location URI format
    pub fn with_invalid_location_uri(mut self) -> Self {
        self.data["meta"]["location"] = json!("not-a-uri");
        self.expected_errors
            .push(ValidationErrorCode::InvalidLocationUri);
        self
    }

    /// Set invalid version format - Error #21: Invalid meta.version format
    pub fn with_invalid_version_format(mut self) -> Self {
        self.data["meta"]["version"] = json!(["invalid", "version"]);
        self.expected_errors
            .push(ValidationErrorCode::InvalidVersionFormat);
        self
    }

    // Attribute type modifications (Errors 22-32)

    /// Set invalid boolean value for active - Error #25: Invalid boolean value
    pub fn with_invalid_boolean_active(mut self) -> Self {
        self.data["active"] = json!("not-boolean"); // Should be true/false
        self.expected_errors
            .push(ValidationErrorCode::InvalidBooleanValue);
        self
    }

    // Multi-valued attribute modifications (Errors 33-38)

    /// Set single value for multi-valued emails - Error #33: Single value for multi-valued
    pub fn with_single_value_emails(mut self) -> Self {
        self.data["emails"] = json!({
            "value": "test@example.com",
            "type": "work"
        });
        self.expected_errors
            .push(ValidationErrorCode::SingleValueForMultiValued);
        self
    }

    /// Set array for single-valued userName - Error #34: Array for single-valued
    pub fn with_array_username(mut self) -> Self {
        self.data["userName"] = json!(["user1", "user2"]);
        self.expected_errors
            .push(ValidationErrorCode::ArrayForSingleValued);
        self
    }

    /// Set invalid string format - Error #24: Invalid string format
    pub fn with_invalid_string_format(mut self) -> Self {
        self.data["userName"] = json!(""); // Empty string for required field
        self.expected_errors
            .push(ValidationErrorCode::InvalidStringFormat);
        self
    }

    /// Set invalid decimal format - Error #26: Invalid decimal format
    pub fn with_invalid_decimal_format(mut self) -> Self {
        self.data["urn:example:decimal"] = json!("not-a-number");
        self.expected_errors
            .push(ValidationErrorCode::InvalidDecimalFormat);
        self
    }

    /// Set invalid integer value - Error #27: Invalid integer value
    pub fn with_invalid_integer_value(mut self) -> Self {
        self.data["urn:example:integer"] = json!("not-an-integer");
        self.expected_errors
            .push(ValidationErrorCode::InvalidIntegerValue);
        self
    }

    /// Set invalid datetime format - Error #28: Invalid datetime format
    pub fn with_invalid_datetime_format(mut self) -> Self {
        self.data["meta"]["created"] = json!("not-a-datetime");
        self.expected_errors
            .push(ValidationErrorCode::InvalidDateTimeFormat);
        self
    }

    /// Set invalid binary data - Error #29: Invalid binary data
    pub fn with_invalid_binary_data(mut self) -> Self {
        self.data["x509Certificates"] = json!([{
            "value": "not-base64!"
        }]);
        self.expected_errors
            .push(ValidationErrorCode::InvalidBinaryData);
        self
    }

    /// Set invalid reference URI - Error #30: Invalid reference URI
    pub fn with_invalid_reference_uri(mut self) -> Self {
        self.data["groups"] = json!([{
            "value": "group-123",
            "$ref": "not-a-uri"
        }]);
        self.expected_errors
            .push(ValidationErrorCode::InvalidReferenceUri);
        self
    }

    /// Set invalid reference type - Error #31: Invalid reference type
    pub fn with_invalid_reference_type(mut self) -> Self {
        self.data["groups"] = json!([{
            "value": "group-123",
            "$ref": "https://example.com/Groups/group-123",
            "type": "invalid-type"
        }]);
        self.expected_errors
            .push(ValidationErrorCode::InvalidReferenceType);
        self
    }

    /// Set broken reference - Error #32: Broken reference
    pub fn with_broken_reference(mut self) -> Self {
        self.data["groups"] = json!([{
            "value": "nonexistent-group",
            "$ref": "https://example.com/Groups/nonexistent-group"
        }]);
        self.expected_errors
            .push(ValidationErrorCode::BrokenReference);
        self
    }

    // Multi-valued attribute modifications (Errors 33-38)
    /// Set multiple primary=true in emails - Error #35: Multiple primary=true values
    pub fn with_multiple_primary_emails(mut self) -> Self {
        self.data["emails"] = json!([
            {
                "value": "primary1@example.com",
                "type": "work",
                "primary": true
            },
            {
                "value": "primary2@example.com",
                "type": "home",
                "primary": true
            }
        ]);
        self.expected_errors
            .push(ValidationErrorCode::MultiplePrimaryValues);
        self
    }

    /// Set invalid canonical value - Error #38: Invalid canonical value
    pub fn with_invalid_email_type(mut self) -> Self {
        self.data["emails"] = json!([
            {
                "value": "test@example.com",
                "type": "invalid-type"
            }
        ]);
        self.expected_errors
            .push(ValidationErrorCode::InvalidCanonicalValue);
        self
    }

    // Complex attribute modifications (Errors 39-43)

    /// Set invalid sub-attribute type in name - Error #40: Invalid sub-attribute type
    pub fn with_invalid_name_sub_attribute_type(mut self) -> Self {
        self.data["name"] = json!({
            "familyName": "Jensen",
            "givenName": 123 // Should be string, not number
        });
        self.expected_errors
            .push(ValidationErrorCode::InvalidSubAttributeType);
        self
    }

    /// Add unknown sub-attribute to name - Error #41: Unknown sub-attribute
    pub fn with_unknown_name_sub_attribute(mut self) -> Self {
        self.data["name"] = json!({
            "familyName": "Jensen",
            "givenName": "Barbara",
            "unknownAttribute": "unknown value"
        });
        self.expected_errors
            .push(ValidationErrorCode::UnknownSubAttribute);
        self
    }

    // Builder methods for valid variations

    /// Set username
    pub fn with_username(mut self, username: &str) -> Self {
        self.data["userName"] = json!(username);
        self
    }

    /// Set display name
    pub fn with_display_name(mut self, display_name: &str) -> Self {
        self.data["displayName"] = json!(display_name);
        self
    }

    /// Add email address
    pub fn with_email(mut self, email: &str, email_type: &str, primary: bool) -> Self {
        let emails = self.data["emails"].as_array().cloned().unwrap_or_default();
        let mut new_emails = emails;
        new_emails.push(json!({
            "value": email,
            "type": email_type,
            "primary": primary
        }));
        self.data["emails"] = json!(new_emails);
        self
    }

    /// Set active status
    pub fn with_active(mut self, active: bool) -> Self {
        self.data["active"] = json!(active);
        self
    }

    // === Enhanced Value Object Methods ===
    // These methods use value objects for construction while maintaining JSON output

    /// Set resource ID using ResourceId value object
    pub fn with_resource_id(mut self, resource_id: ResourceId) -> Self {
        self.data["id"] = json!(resource_id.as_str());
        self
    }

    /// Set schema URIs using SchemaUri value objects
    pub fn with_schema_uris(mut self, schema_uris: Vec<SchemaUri>) -> Self {
        let uri_strings: Vec<String> = schema_uris
            .into_iter()
            .map(|uri| uri.as_str().to_string())
            .collect();
        self.data["schemas"] = json!(uri_strings);
        self
    }

    /// Set external ID using ExternalId value object
    pub fn with_external_id_value_object(mut self, external_id: ExternalId) -> Self {
        self.data["externalId"] = json!(external_id.as_str());
        self
    }

    /// Set user name using UserName value object
    pub fn with_user_name_value_object(mut self, user_name: UserName) -> Self {
        self.data["userName"] = json!(user_name.as_str());
        self
    }

    /// Create a builder with validated value objects (convenience method)
    pub fn new_with_value_objects(
        resource_id: ResourceId,
        user_name: UserName,
        schema_uris: Vec<SchemaUri>,
    ) -> Self {
        Self::new()
            .with_resource_id(resource_id)
            .with_user_name_value_object(user_name)
            .with_schema_uris(schema_uris)
    }

    /// Try to extract value objects from current builder state
    pub fn extract_value_objects(
        &self,
    ) -> (
        Option<ResourceId>,
        Option<UserName>,
        Option<ExternalId>,
        Vec<SchemaUri>,
    ) {
        let resource_id = self
            .data
            .get("id")
            .and_then(|v| v.as_str())
            .and_then(|s| ResourceId::new(s.to_string()).ok());

        let user_name = self
            .data
            .get("userName")
            .and_then(|v| v.as_str())
            .and_then(|s| UserName::new(s.to_string()).ok());

        let external_id = self
            .data
            .get("externalId")
            .and_then(|v| v.as_str())
            .and_then(|s| ExternalId::new(s.to_string()).ok());

        let schema_uris = self
            .data
            .get("schemas")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str())
                    .filter_map(|s| SchemaUri::new(s.to_string()).ok())
                    .collect()
            })
            .unwrap_or_default();

        (resource_id, user_name, external_id, schema_uris)
    }

    /// Build the final JSON value
    pub fn build(self) -> Value {
        self.data
    }

    /// Get expected validation errors for this builder configuration
    pub fn expected_errors(&self) -> &[ValidationErrorCode] {
        &self.expected_errors
    }
}

impl Default for UserBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Builder for Group resources
#[derive(Debug, Clone)]
pub struct GroupBuilder {
    data: Value,
    expected_errors: Vec<ValidationErrorCode>,
}

impl GroupBuilder {
    /// Create a new GroupBuilder with minimal valid Group data
    pub fn new() -> Self {
        Self {
            data: json!({
                "schemas": ["urn:ietf:params:scim:schemas:core:2.0:Group"],
                "id": "e9e30dba-f08f-4109-8486-d5c6a331660a",
                "displayName": "Tour Guides",
                "meta": {
                    "resourceType": "Group",
                    "created": "2010-01-23T04:56:22Z",
                    "lastModified": "2011-05-13T04:42:34Z",
                    "version": "W/\"3694e05e9dff592\"",
                    "location": "https://example.com/v2/Groups/e9e30dba-f08f-4109-8486-d5c6a331660a"
                }
            }),
            expected_errors: Vec::new(),
        }
    }

    /// Remove displayName - Group-specific required attribute
    pub fn without_display_name(mut self) -> Self {
        self.data.as_object_mut().unwrap().remove("displayName");
        self.expected_errors
            .push(ValidationErrorCode::MissingRequiredAttribute);
        self
    }

    /// Set empty displayName
    pub fn with_empty_display_name(mut self) -> Self {
        self.data["displayName"] = json!("");
        self.expected_errors
            .push(ValidationErrorCode::MissingRequiredAttribute);
        self
    }

    /// Set displayName
    pub fn with_display_name(mut self, display_name: &str) -> Self {
        self.data["displayName"] = json!(display_name);
        self
    }

    /// Add member to group
    pub fn with_member(
        mut self,
        user_id: &str,
        user_ref: &str,
        display_name: Option<&str>,
    ) -> Self {
        let members = self.data["members"].as_array().cloned().unwrap_or_default();
        let mut new_members = members;
        let mut member = json!({
            "value": user_id,
            "$ref": user_ref,
            "type": "User"
        });
        if let Some(name) = display_name {
            member["display"] = json!(name);
        }
        new_members.push(member);
        self.data["members"] = json!(new_members);
        self
    }

    /// Build the final JSON value
    pub fn build(self) -> Value {
        self.data
    }

    /// Get expected validation errors for this builder configuration
    pub fn expected_errors(&self) -> &[ValidationErrorCode] {
        &self.expected_errors
    }
}

impl Default for GroupBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Builder for Schema resources
#[derive(Debug, Clone)]
pub struct SchemaBuilder {
    data: Value,
}

impl SchemaBuilder {
    /// Create a new SchemaBuilder with basic User schema structure
    pub fn new_user_schema() -> Self {
        Self {
            data: json!({
                "id": "urn:ietf:params:scim:schemas:core:2.0:User",
                "name": "User",
                "description": "User Account",
                "attributes": [
                    {
                        "name": "userName",
                        "type": "string",
                        "multiValued": false,
                        "required": true,
                        "caseExact": false,
                        "mutability": "readWrite",
                        "returned": "default",
                        "uniqueness": "server"
                    }
                ]
            }),
        }
    }

    /// Build the final JSON value
    pub fn build(self) -> Value {
        self.data
    }
}

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

    #[test]
    fn test_user_builder_new() {
        let user = UserBuilder::new().build();
        assert_eq!(
            user["schemas"][0],
            "urn:ietf:params:scim:schemas:core:2.0:User"
        );
        assert_eq!(user["userName"], "bjensen@example.com");
        assert!(!user["id"].as_str().unwrap().is_empty());
    }

    #[test]
    fn test_user_builder_without_schemas() {
        let builder = UserBuilder::new().without_schemas();
        let user = builder.build();
        assert!(!user.as_object().unwrap().contains_key("schemas"));

        let builder2 = UserBuilder::new().without_schemas();
        let expected_errors = builder2.expected_errors();
        assert_eq!(expected_errors, &[ValidationErrorCode::MissingSchemas]);
    }

    #[test]
    fn test_user_builder_with_empty_schemas() {
        let builder = UserBuilder::new().with_empty_schemas();
        let user = builder.build();
        assert_eq!(user["schemas"], json!([]));

        let builder2 = UserBuilder::new().with_empty_schemas();
        assert_eq!(
            builder2.expected_errors(),
            &[ValidationErrorCode::EmptySchemas]
        );
    }

    #[test]
    fn test_user_builder_multiple_errors() {
        let builder = UserBuilder::new().without_schemas().without_username();
        let expected_errors = builder.expected_errors();
        assert_eq!(expected_errors.len(), 2);
        assert!(expected_errors.contains(&ValidationErrorCode::MissingSchemas));
        assert!(expected_errors.contains(&ValidationErrorCode::MissingRequiredAttribute));
    }

    #[test]
    fn test_group_builder_new() {
        let group = GroupBuilder::new().build();
        assert_eq!(
            group["schemas"][0],
            "urn:ietf:params:scim:schemas:core:2.0:Group"
        );
        assert_eq!(group["displayName"], "Tour Guides");
    }

    #[test]
    fn test_group_builder_without_display_name() {
        let builder = GroupBuilder::new().without_display_name();
        let group = builder.build();
        assert!(!group.as_object().unwrap().contains_key("displayName"));

        let builder2 = GroupBuilder::new().without_display_name();
        assert_eq!(
            builder2.expected_errors(),
            &[ValidationErrorCode::MissingRequiredAttribute]
        );
    }
}