gouqi 0.20.0

Rust interface for Jira
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
// Third party
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::path::Path;
use std::time::Duration;
use url::Url;
use url::form_urlencoded;

// Ours
use crate::{
    Credentials, Error, GouqiConfig, Result,
    env::{load_config_from_env, load_credentials_from_env, load_host_from_env},
};

/// Options availble for search
#[derive(Default, Clone, Debug)]
pub struct SearchOptions {
    params: BTreeMap<&'static str, String>,
    fields_explicitly_set: bool,
}

impl SearchOptions {
    /// Return a new instance of a builder for options
    pub fn builder() -> SearchOptionsBuilder {
        SearchOptionsBuilder::new()
    }

    /// Serialize options as a string. returns None if no options are defined
    pub fn serialize(&self) -> Option<String> {
        if self.params.is_empty() {
            None
        } else {
            Some(
                form_urlencoded::Serializer::new(String::new())
                    .extend_pairs(&self.params)
                    .finish(),
            )
        }
    }

    pub fn as_builder(&self) -> SearchOptionsBuilder {
        SearchOptionsBuilder::copy_from(self)
    }

    /// Check if fields were explicitly set by the user
    pub fn fields_explicitly_set(&self) -> bool {
        self.fields_explicitly_set
    }

    /// Get the start_at value from search options
    pub fn start_at(&self) -> Option<u64> {
        self.params.get("startAt").and_then(|s| s.parse().ok())
    }

    /// Get the max_results value from search options  
    pub fn max_results(&self) -> Option<u64> {
        self.params.get("maxResults").and_then(|s| s.parse().ok())
    }
}

/// A builder interface for search option. Typically this
/// is initialized with SearchOptions::builder()
#[derive(Default, Debug)]
pub struct SearchOptionsBuilder {
    params: BTreeMap<&'static str, String>,
    fields_explicitly_set: bool,
}

impl SearchOptionsBuilder {
    pub fn new() -> SearchOptionsBuilder {
        SearchOptionsBuilder {
            ..Default::default()
        }
    }

    fn copy_from(search_options: &SearchOptions) -> SearchOptionsBuilder {
        SearchOptionsBuilder {
            params: search_options.params.clone(),
            fields_explicitly_set: search_options.fields_explicitly_set,
        }
    }

    pub fn fields<F>(&mut self, fs: Vec<F>) -> &mut SearchOptionsBuilder
    where
        F: Into<String>,
    {
        self.params.insert(
            "fields",
            fs.into_iter()
                .map(|f| f.into())
                .collect::<Vec<String>>()
                .join(","),
        );
        self.fields_explicitly_set = true;
        self
    }

    pub fn validate(&mut self, v: bool) -> &mut SearchOptionsBuilder {
        self.params.insert("validateQuery", v.to_string());
        self
    }

    pub fn max_results(&mut self, m: u64) -> &mut SearchOptionsBuilder {
        self.params.insert("maxResults", m.to_string());
        self
    }

    pub fn start_at(&mut self, s: u64) -> &mut SearchOptionsBuilder {
        self.params.insert("startAt", s.to_string());
        self
    }

    pub fn type_name(&mut self, t: &str) -> &mut SearchOptionsBuilder {
        self.params.insert("type", t.to_string());
        self
    }

    pub fn name(&mut self, n: &str) -> &mut SearchOptionsBuilder {
        self.params.insert("name", n.to_string());
        self
    }

    pub fn project_key_or_id(&mut self, id: &str) -> &mut SearchOptionsBuilder {
        self.params.insert("projectKeyOrId", id.to_string());
        self
    }

    pub fn expand<E>(&mut self, ex: Vec<E>) -> &mut SearchOptionsBuilder
    where
        E: Into<String>,
    {
        self.params.insert(
            "expand",
            ex.into_iter()
                .map(|e| e.into())
                .collect::<Vec<String>>()
                .join(","),
        );
        self
    }

    pub fn properties<P>(&mut self, props: Vec<P>) -> &mut SearchOptionsBuilder
    where
        P: Into<String>,
    {
        self.params.insert(
            "properties",
            props
                .into_iter()
                .map(|p| p.into())
                .collect::<Vec<String>>()
                .join(","),
        );
        self
    }

    pub fn state(&mut self, s: &str) -> &mut SearchOptionsBuilder {
        self.params.insert("state", s.to_string());
        self
    }

    pub fn jql(&mut self, s: &str) -> &mut SearchOptionsBuilder {
        self.params.insert("jql", s.to_string());
        self
    }

    pub fn validate_query(&mut self, v: bool) -> &mut SearchOptionsBuilder {
        self.params.insert("validateQuery", v.to_string());
        self
    }

    /// Internal method for V3 API pagination with nextPageToken
    /// This is not part of the public API and should only be used internally
    #[doc(hidden)]
    pub fn next_page_token(&mut self, token: &str) -> &mut SearchOptionsBuilder {
        self.params.insert("nextPageToken", token.to_string());
        self
    }

    /// Convenience method for essential fields needed for Issue struct compatibility
    pub fn essential_fields(&mut self) -> &mut SearchOptionsBuilder {
        self.fields(vec!["id", "self", "key", "summary", "status"])
    }

    /// Convenience method for commonly used fields
    pub fn standard_fields(&mut self) -> &mut SearchOptionsBuilder {
        self.fields(vec![
            "id", "self", "key", "summary", "status", "assignee", "reporter", "created", "updated",
        ])
    }

    /// Convenience method for all available fields
    pub fn all_fields(&mut self) -> &mut SearchOptionsBuilder {
        self.fields(vec!["*all"])
    }

    /// Convenience method for minimal response (only id field)
    pub fn minimal_fields(&mut self) -> &mut SearchOptionsBuilder {
        self.fields(vec!["id"])
    }

    pub fn build(&self) -> SearchOptions {
        SearchOptions {
            params: self.params.clone(),
            fields_explicitly_set: self.fields_explicitly_set,
        }
    }
}

/// Enhanced builder for Jira client configuration
///
/// This builder provides a fluent interface for configuring all aspects of the Jira client,
/// including authentication, timeouts, connection pools, caching, metrics, and custom fields.
///
/// # Examples
///
/// ```rust,no_run
/// use gouqi::{JiraBuilder, Credentials, FieldSchema};
/// use std::time::Duration;
///
/// // Basic usage
/// let jira = JiraBuilder::new()
///     .host("https://company.atlassian.net")
///     .credentials(Credentials::Basic("user".to_string(), "token".to_string()))
///     .timeout(Duration::from_secs(60))
///     .build_with_validation()?;
///
/// // Advanced configuration
/// let jira = JiraBuilder::new()
///     .host("https://company.atlassian.net")
///     .credentials(Credentials::Bearer("token".to_string()))
///     .config_from_file("config.yaml")?
///     .custom_field("story_points", FieldSchema::number(false, Some(0.0), Some(100.0)))
///     .memory_cache(Duration::from_secs(300), 1000)
///     .retry_policy(3, Duration::from_millis(500), Duration::from_secs(10))
///     .build_with_validation()?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone)]
pub struct JiraBuilder {
    host: Option<String>,
    credentials: Option<Credentials>,
    config: GouqiConfig,
    custom_fields: HashMap<String, FieldSchema>,
    validate_ssl: bool,
    user_agent: Option<String>,
}

impl JiraBuilder {
    /// Create a new builder with default configuration
    pub fn new() -> Self {
        Self {
            host: None,
            credentials: None,
            config: GouqiConfig::default(),
            custom_fields: HashMap::new(),
            validate_ssl: true,
            user_agent: None,
        }
    }

    /// Set Jira host URL
    ///
    /// # Panics
    ///
    /// This function will panic if the URL is invalid
    pub fn host<H: Into<String>>(mut self, host: H) -> Self {
        let host_str = host.into();

        // Validate URL format
        if Url::parse(&host_str).is_err() {
            panic!("Invalid host URL: {}", host_str);
        }

        self.host = Some(host_str);
        self
    }

    /// Set authentication credentials
    pub fn credentials(mut self, credentials: Credentials) -> Self {
        self.credentials = Some(credentials);
        self
    }

    /// Load configuration from file (JSON, YAML, or TOML)
    ///
    /// # Panics
    ///
    /// This function will panic if the config file cannot be read or parsed
    pub fn config_from_file<P: AsRef<Path>>(mut self, path: P) -> Result<Self> {
        let config = GouqiConfig::from_file(path)?;
        self.config = self.config.merge(config);
        Ok(self)
    }

    /// Load configuration from environment variables
    ///
    /// This will load host, credentials, and various configuration options from
    /// environment variables with the `JIRA_` prefix.
    pub fn config_from_env(mut self) -> Result<Self> {
        // Load host if not already set
        if self.host.is_none() {
            if let Some(host) = load_host_from_env() {
                self = self.host(host);
            }
        }

        // Load credentials if not already set
        if self.credentials.is_none() {
            let creds = load_credentials_from_env();
            if !matches!(creds, Credentials::Anonymous) {
                self = self.credentials(creds);
            }
        }

        // Merge environment configuration
        let env_config = load_config_from_env();
        self.config = self.config.merge(env_config);

        Ok(self)
    }

    /// Apply a predefined configuration template
    pub fn config_template(mut self, template: ConfigTemplate) -> Self {
        self.config = match template {
            ConfigTemplate::Default => GouqiConfig::default(),
            ConfigTemplate::HighThroughput => GouqiConfig::high_throughput(),
            ConfigTemplate::LowResource => GouqiConfig::low_resource(),
        };
        self
    }

    /// Set request timeout
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.config.timeout.default = timeout;
        self
    }

    /// Set connection timeout  
    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
        self.config.timeout.connect = timeout;
        self
    }

    /// Set read timeout
    pub fn read_timeout(mut self, timeout: Duration) -> Self {
        self.config.timeout.read = timeout;
        self
    }

    /// Configure retry policy
    pub fn retry_policy(
        mut self,
        max_attempts: u32,
        base_delay: Duration,
        max_delay: Duration,
    ) -> Self {
        self.config.retry.max_attempts = max_attempts;
        self.config.retry.base_delay = base_delay;
        self.config.retry.max_delay = max_delay;
        self
    }

    /// Set retry backoff multiplier
    pub fn retry_backoff(mut self, multiplier: f64) -> Self {
        self.config.retry.backoff_multiplier = multiplier;
        self
    }

    /// Set which HTTP status codes should trigger retries
    pub fn retry_status_codes(mut self, codes: Vec<u16>) -> Self {
        self.config.retry.retry_status_codes = codes;
        self
    }

    /// Set connection pool size
    pub fn connection_pool_size(mut self, size: usize) -> Self {
        self.config.connection_pool.max_connections_per_host = size;
        self
    }

    /// Configure connection pool settings
    pub fn connection_pool(
        mut self,
        max_connections: usize,
        idle_timeout: Duration,
        http2: bool,
    ) -> Self {
        self.config.connection_pool.max_connections_per_host = max_connections;
        self.config.connection_pool.idle_timeout = idle_timeout;
        self.config.connection_pool.http2 = http2;
        self
    }

    /// Enable or disable SSL certificate validation
    pub fn validate_ssl(mut self, validate: bool) -> Self {
        self.validate_ssl = validate;
        self
    }

    /// Set custom User-Agent header
    pub fn user_agent<S: Into<String>>(mut self, user_agent: S) -> Self {
        self.user_agent = Some(user_agent.into());
        self
    }

    /// Enable caching with default settings
    pub fn enable_cache(mut self) -> Self {
        self.config.cache.enabled = true;
        self
    }

    /// Disable caching
    pub fn disable_cache(mut self) -> Self {
        self.config.cache.enabled = false;
        self
    }

    /// Configure memory cache with custom settings
    pub fn memory_cache(mut self, default_ttl: Duration, max_entries: usize) -> Self {
        self.config.cache.enabled = true;
        self.config.cache.default_ttl = default_ttl;
        self.config.cache.max_entries = max_entries;
        self
    }

    /// Configure rate limiting
    pub fn rate_limit(mut self, requests_per_second: f64, burst_capacity: u32) -> Self {
        self.config.rate_limiting.enabled = true;
        self.config.rate_limiting.requests_per_second = requests_per_second;
        self.config.rate_limiting.burst_capacity = burst_capacity;
        self
    }

    /// Disable rate limiting
    pub fn disable_rate_limiting(mut self) -> Self {
        self.config.rate_limiting.enabled = false;
        self
    }

    /// Enable metrics collection
    pub fn enable_metrics(mut self) -> Self {
        self.config.metrics.enabled = true;
        self
    }

    /// Disable metrics collection
    pub fn disable_metrics(mut self) -> Self {
        self.config.metrics.enabled = false;
        self
    }

    /// Configure metrics collection settings
    pub fn metrics_config(mut self, collection_interval: Duration, export_format: &str) -> Self {
        self.config.metrics.enabled = true;
        self.config.metrics.collection_interval = collection_interval;
        self.config.metrics.export.format = export_format.to_string();
        self
    }

    /// Add custom field schema
    ///
    /// # Panics
    ///
    /// This function will panic if the field name is empty
    pub fn custom_field<N: Into<String>>(mut self, name: N, schema: FieldSchema) -> Self {
        let field_name = name.into();
        assert!(!field_name.is_empty(), "Field name cannot be empty");

        self.custom_fields.insert(field_name, schema);
        self
    }

    /// Add multiple custom fields
    pub fn custom_fields(mut self, fields: HashMap<String, FieldSchema>) -> Self {
        self.custom_fields.extend(fields);
        self
    }

    /// Build and validate the configuration
    ///
    /// This method performs comprehensive validation of all configuration settings
    /// and returns an error if any issues are found.
    ///
    /// # Panics
    ///
    /// This function will panic if the configuration is invalid
    pub fn build_with_validation(self) -> Result<crate::Jira> {
        // Validate required fields - use clone to avoid move
        let host = self.host.clone().ok_or_else(|| Error::ConfigError {
            message: "Host URL is required".to_string(),
        })?;

        let credentials = self.credentials.clone().ok_or_else(|| Error::ConfigError {
            message: "Credentials are required".to_string(),
        })?;

        // Validate host URL
        let _parsed_url = Url::parse(&host).map_err(|e| Error::ConfigError {
            message: format!("Invalid host URL '{}': {}", host, e),
        })?;

        // Validate configuration
        self.config.validate()?;

        // Validate credentials
        self.validate_credentials(&credentials)?;

        // Validate custom fields
        self.validate_custom_fields()?;

        // Build the client
        self.build()
    }

    /// Build the Jira client (without validation)
    ///
    /// This method builds the client without performing validation.
    /// Use `build_with_validation()` for production code.
    pub fn build(self) -> Result<crate::Jira> {
        let host = self
            .host
            .unwrap_or_else(|| "http://localhost:8080".to_string());
        let credentials = self.credentials.unwrap_or(Credentials::Anonymous);

        // Create the basic client
        let client = crate::Jira::new(host, credentials)?;

        // TODO: Apply advanced configuration to the client
        // This would require extending the core client to support these features

        Ok(client)
    }

    /// Validate credentials
    fn validate_credentials(&self, credentials: &Credentials) -> Result<()> {
        match credentials {
            Credentials::Basic(user, pass) => {
                if user.is_empty() || pass.is_empty() {
                    return Err(Error::ConfigError {
                        message: "Username and password cannot be empty for Basic auth".to_string(),
                    });
                }
            }
            Credentials::Bearer(token) => {
                if token.is_empty() {
                    return Err(Error::ConfigError {
                        message: "Bearer token cannot be empty".to_string(),
                    });
                }
            }
            Credentials::Cookie(cookie) => {
                if cookie.is_empty() {
                    return Err(Error::ConfigError {
                        message: "Cookie cannot be empty".to_string(),
                    });
                }
            }
            #[cfg(feature = "oauth")]
            Credentials::OAuth1a {
                consumer_key,
                private_key_pem,
                access_token,
                access_token_secret,
            } => {
                if consumer_key.is_empty() {
                    return Err(Error::ConfigError {
                        message: "OAuth consumer key cannot be empty".to_string(),
                    });
                }
                if private_key_pem.is_empty() {
                    return Err(Error::ConfigError {
                        message: "OAuth private key cannot be empty".to_string(),
                    });
                }
                if access_token.is_empty() {
                    return Err(Error::ConfigError {
                        message: "OAuth access token cannot be empty".to_string(),
                    });
                }
                if access_token_secret.is_empty() {
                    return Err(Error::ConfigError {
                        message: "OAuth access token secret cannot be empty".to_string(),
                    });
                }
            }
            Credentials::Anonymous => {
                // Anonymous is always valid
            }
        }
        Ok(())
    }

    /// Validate custom field schemas
    fn validate_custom_fields(&self) -> Result<()> {
        for (field_name, schema) in &self.custom_fields {
            schema.validate(field_name)?;
        }
        Ok(())
    }

    /// Getter methods for testing
    #[cfg(test)]
    pub fn get_host(&self) -> &Option<String> {
        &self.host
    }

    #[cfg(test)]
    pub fn get_credentials(&self) -> &Option<Credentials> {
        &self.credentials
    }

    #[cfg(test)]
    pub fn get_config(&self) -> &GouqiConfig {
        &self.config
    }

    #[cfg(test)]
    pub fn get_custom_fields(&self) -> &HashMap<String, FieldSchema> {
        &self.custom_fields
    }
}

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

/// Predefined configuration templates
#[derive(Debug, Clone, Copy)]
pub enum ConfigTemplate {
    /// Default balanced configuration
    Default,
    /// Optimized for high-throughput scenarios
    HighThroughput,
    /// Optimized for low-resource environments
    LowResource,
}

/// Custom field schema definition for Jira fields
///
/// This allows you to define validation rules and metadata for custom fields
/// that your application uses with Jira.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FieldSchema {
    /// The type of field (string, number, enum, etc.)
    pub field_type: String,
    /// Whether this field is required
    pub required: bool,
    /// Default value for the field
    pub default_value: Option<serde_json::Value>,
    /// Allowed values (for enum-type fields)
    pub allowed_values: Option<Vec<serde_json::Value>>,
    /// Custom properties for validation
    pub custom_properties: HashMap<String, serde_json::Value>,
}

impl FieldSchema {
    /// Create a simple text field schema
    pub fn text(required: bool) -> Self {
        Self {
            field_type: "string".to_string(),
            required,
            default_value: None,
            allowed_values: None,
            custom_properties: HashMap::new(),
        }
    }

    /// Create a number field schema with optional min/max validation
    ///
    /// # Panics
    ///
    /// This function will panic if min is greater than max
    pub fn number(required: bool, min: Option<f64>, max: Option<f64>) -> Self {
        let mut properties = HashMap::new();

        if let (Some(min_val), Some(max_val)) = (min, max) {
            assert!(
                min_val <= max_val,
                "Minimum value cannot be greater than maximum value"
            );
        }

        if let Some(min_val) = min {
            properties.insert(
                "minimum".to_string(),
                serde_json::Value::Number(serde_json::Number::from_f64(min_val).unwrap()),
            );
        }
        if let Some(max_val) = max {
            properties.insert(
                "maximum".to_string(),
                serde_json::Value::Number(serde_json::Number::from_f64(max_val).unwrap()),
            );
        }

        Self {
            field_type: "number".to_string(),
            required,
            default_value: None,
            allowed_values: None,
            custom_properties: properties,
        }
    }

    /// Create an integer field schema with optional min/max validation
    ///
    /// # Panics
    ///
    /// This function will panic if min is greater than max
    pub fn integer(required: bool, min: Option<i64>, max: Option<i64>) -> Self {
        let mut properties = HashMap::new();

        if let (Some(min_val), Some(max_val)) = (min, max) {
            assert!(
                min_val <= max_val,
                "Minimum value cannot be greater than maximum value"
            );
        }

        if let Some(min_val) = min {
            properties.insert(
                "minimum".to_string(),
                serde_json::Value::Number(serde_json::Number::from(min_val)),
            );
        }
        if let Some(max_val) = max {
            properties.insert(
                "maximum".to_string(),
                serde_json::Value::Number(serde_json::Number::from(max_val)),
            );
        }

        Self {
            field_type: "integer".to_string(),
            required,
            default_value: None,
            allowed_values: None,
            custom_properties: properties,
        }
    }

    /// Create a boolean field schema
    pub fn boolean(required: bool, default: Option<bool>) -> Self {
        Self {
            field_type: "boolean".to_string(),
            required,
            default_value: default.map(serde_json::Value::Bool),
            allowed_values: None,
            custom_properties: HashMap::new(),
        }
    }

    /// Create an enum field schema with allowed values
    pub fn enumeration<V: Serialize>(required: bool, allowed_values: Vec<V>) -> Result<Self> {
        let values: std::result::Result<Vec<serde_json::Value>, crate::Error> = allowed_values
            .into_iter()
            .map(|v| serde_json::to_value(v).map_err(Error::Serde))
            .collect();

        Ok(Self {
            field_type: "enum".to_string(),
            required,
            default_value: None,
            allowed_values: Some(values?),
            custom_properties: HashMap::new(),
        })
    }

    /// Create a date field schema
    pub fn date(required: bool) -> Self {
        Self {
            field_type: "date".to_string(),
            required,
            default_value: None,
            allowed_values: None,
            custom_properties: HashMap::new(),
        }
    }

    /// Create a datetime field schema
    pub fn datetime(required: bool) -> Self {
        Self {
            field_type: "datetime".to_string(),
            required,
            default_value: None,
            allowed_values: None,
            custom_properties: HashMap::new(),
        }
    }

    /// Create an array field schema
    pub fn array(required: bool, item_type: &str) -> Self {
        let mut properties = HashMap::new();
        properties.insert(
            "item_type".to_string(),
            serde_json::Value::String(item_type.to_string()),
        );

        Self {
            field_type: "array".to_string(),
            required,
            default_value: None,
            allowed_values: None,
            custom_properties: properties,
        }
    }

    /// Set a default value for the field
    pub fn with_default<V: Serialize>(mut self, default: V) -> Result<Self> {
        self.default_value = Some(serde_json::to_value(default).map_err(Error::Serde)?);
        Ok(self)
    }

    /// Add a custom property to the schema
    pub fn with_property<V: Serialize>(mut self, key: &str, value: V) -> Result<Self> {
        self.custom_properties.insert(
            key.to_string(),
            serde_json::to_value(value).map_err(Error::Serde)?,
        );
        Ok(self)
    }

    /// Validate the field schema
    fn validate(&self, field_name: &str) -> Result<()> {
        if self.field_type.is_empty() {
            return Err(Error::FieldSchemaError {
                field: field_name.to_string(),
                message: "Field type cannot be empty".to_string(),
            });
        }

        // Validate enum fields have allowed values
        if self.field_type == "enum" && self.allowed_values.is_none() {
            return Err(Error::FieldSchemaError {
                field: field_name.to_string(),
                message: "Enum fields must specify allowed values".to_string(),
            });
        }

        // Validate number/integer ranges
        if matches!(self.field_type.as_str(), "number" | "integer") {
            if let (Some(min), Some(max)) = (
                self.custom_properties
                    .get("minimum")
                    .and_then(|v| v.as_f64()),
                self.custom_properties
                    .get("maximum")
                    .and_then(|v| v.as_f64()),
            ) {
                if min > max {
                    return Err(Error::FieldSchemaError {
                        field: field_name.to_string(),
                        message: "Minimum value cannot be greater than maximum value".to_string(),
                    });
                }
            }
        }

        // Validate array item types
        if self.field_type == "array" && !self.custom_properties.contains_key("item_type") {
            return Err(Error::FieldSchemaError {
                field: field_name.to_string(),
                message: "Array fields must specify item_type".to_string(),
            });
        }

        Ok(())
    }
}