cal-core 0.2.158

Callable core lib
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
// File: cal-core/src/rest/common.rs

use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;
use std::fmt;
#[cfg(feature = "openapi")]
use utoipa::ToSchema;

/// Unified API response that can handle all response types
#[derive(Debug, Serialize, Deserialize, Clone)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(
    title = "Unified API response for all endpoints",
    example = json!({
        "status": "success",
        "type": "single",
        "dataType": "Contact",
        "source": "/api/v1/contacts",
        "data": {
            "id": "507f1f77bcf86cd799439011",
            "name": "John Doe"
        }
    })
))]
#[serde(rename_all = "camelCase")]
pub struct UnifiedApiResponse {
    /// Response status: "success" or "error"
    pub status: ResponseStatus,

    /// Type of response: "single", "list", "paginated", "batch", "empty"
    #[serde(rename = "type")]
    pub response_type: ResponseType,

    /// The type of data being returned (e.g., "Contact", "Account", "Device")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_type: Option<String>,

    /// The source endpoint that generated this response
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,

    /// Optional data field - can contain any JSON value
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<Value>,

    /// Optional error information
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<ApiError>,

    /// Optional pagination information
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pagination: Option<PaginationMeta>,

    /// Optional metadata
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<ResponseMetadata>,

    /// For batch operations
    #[serde(skip_serializing_if = "Option::is_none")]
    pub batch_results: Option<BatchResults>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(title = "Response status indicator"))]
#[serde(rename_all = "lowercase")]
pub enum ResponseStatus {
    Success,
    Error,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(title = "Type of response data"))]
#[serde(rename_all = "lowercase")]
pub enum ResponseType {
    Single,
    List,
    Paginated,
    Batch,
    Empty,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(title = "Results of a batch operation"))]
#[serde(rename_all = "camelCase")]
pub struct BatchResults {
    pub succeeded: Vec<Value>,
    pub failed: Vec<BatchErrorItem>,
    pub total: usize,
    pub success_count: usize,
    pub failure_count: usize,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(title = "Error details for a failed batch item"))]
#[serde(rename_all = "camelCase")]
pub struct BatchErrorItem {
    /// Index of the item in the original batch
    #[cfg_attr(feature = "openapi", schema(example = 42))]
    pub index: usize,

    /// Optional ID of the item that failed
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = "507f1f77bcf86cd799439011"))]
    pub id: Option<String>,

    /// The item that failed
    pub item: Value,

    /// Error that occurred for this item
    pub error: ApiError,
}

// Helper implementations for UnifiedApiResponse
impl UnifiedApiResponse {
    /// Create a successful single item response
    pub fn single<T: Serialize>(item: T, data_type: &str, source: &str) -> Self {
        Self {
            status: ResponseStatus::Success,
            response_type: ResponseType::Single,
            data_type: Some(data_type.to_string()),
            source: Some(source.to_string()),
            data: Some(serde_json::to_value(item).unwrap()),
            error: None,
            pagination: None,
            metadata: None,
            batch_results: None,
        }
    }

    /// Create a successful list response
    pub fn list<T: Serialize>(items: Vec<T>, data_type: &str, source: &str) -> Self {
        Self {
            status: ResponseStatus::Success,
            response_type: ResponseType::List,
            data_type: Some(format!("List<{}>", data_type)),
            source: Some(source.to_string()),
            data: Some(serde_json::to_value(items).unwrap()),
            error: None,
            pagination: None,
            metadata: None,
            batch_results: None,
        }
    }

    /// Create a paginated response
    pub fn paginated<T: Serialize>(
        items: Vec<T>,
        pagination: PaginationMeta,
        data_type: &str,
        source: &str
    ) -> Self {
        Self {
            status: ResponseStatus::Success,
            response_type: ResponseType::Paginated,
            data_type: Some(format!("Paginated<{}>", data_type)),
            source: Some(source.to_string()),
            data: Some(serde_json::to_value(items).unwrap()),
            error: None,
            pagination: Some(pagination),
            metadata: None,
            batch_results: None,
        }
    }

    /// Create an error response
    pub fn error(error: ApiError, source: &str) -> Self {
        Self {
            status: ResponseStatus::Error,
            response_type: ResponseType::Empty,
            data_type: None,
            source: Some(source.to_string()),
            data: None,
            error: Some(error),
            pagination: None,
            metadata: None,
            batch_results: None,
        }
    }

    /// Create an empty success response (e.g., for DELETE)
    pub fn empty(source: &str) -> Self {
        Self {
            status: ResponseStatus::Success,
            response_type: ResponseType::Empty,
            data_type: None,
            source: Some(source.to_string()),
            data: None,
            error: None,
            pagination: None,
            metadata: None,
            batch_results: None,
        }
    }

    /// Create a batch response
    pub fn batch<T: Serialize, E: Serialize>(
        succeeded: Vec<T>,
        failed: Vec<(usize, Option<String>, E, ApiError)>,
        data_type: &str,
        source: &str
    ) -> Self {
        let succeeded_values: Vec<Value> = succeeded
            .into_iter()
            .map(|item| serde_json::to_value(item).unwrap())
            .collect();

        let failed_items: Vec<BatchErrorItem> = failed
            .into_iter()
            .map(|(index, id, item, error)| BatchErrorItem {
                index,
                id,
                item: serde_json::to_value(item).unwrap(),
                error,
            })
            .collect();

        let total = succeeded_values.len() + failed_items.len();
        let success_count = succeeded_values.len();
        let failure_count = failed_items.len();

        Self {
            status: if failure_count == 0 {
                ResponseStatus::Success
            } else {
                ResponseStatus::Error
            },
            response_type: ResponseType::Batch,
            data_type: Some(format!("Batch<{}>", data_type)),
            source: Some(source.to_string()),
            data: None,
            error: None,
            pagination: None,
            metadata: None,
            batch_results: Some(BatchResults {
                succeeded: succeeded_values,
                failed: failed_items,
                total,
                success_count,
                failure_count,
            }),
        }
    }

    /// Add metadata to the response
    pub fn with_metadata(mut self, metadata: ResponseMetadata) -> Self {
        self.metadata = Some(metadata);
        self
    }
}

/// Response for synchronization operations
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(
    title ="Response returned from synchronization endpoints",
    example = json!({
        "status": "success",
        "message": "Synchronization started successfully"
    })
))]
pub struct SyncResponse {
    /// Status of the sync operation (e.g., "success", "failed", "pending")
    #[cfg_attr(feature = "openapi", schema(example = "success"))]
    pub status: String,

    /// Descriptive message about the sync operation
    #[cfg_attr(feature = "openapi", schema(example = "Contact sync started in background"))]
    pub message: String,
}

/// Response from cache operations
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(
    title ="Response containing data retrieved from cache"
))]
pub struct CacheResponse {
    /// Source of the data (typically "cache")
    #[cfg_attr(feature = "openapi", schema(example = "cache"))]
    pub source: String,

    /// The cached data as a JSON value
    pub data: serde_json::Value,

    /// Optional count of items in the data
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = 42))]
    pub count: Option<usize>,

    /// Additional information about the cached data
    #[serde(skip_serializing_if = "Option::is_none")]
    pub additional_info: Option<serde_json::Value>,
}

/// Error response from cache operations
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(
    title ="Error response when cache operation fails"
))]
pub struct CacheErrorResponse {
    /// Error message describing what went wrong
    #[cfg_attr(feature = "openapi", schema(example = "Redis connection timeout"))]
    pub error: String,

    /// Source of the error (typically "cache")
    #[cfg_attr(feature = "openapi", schema(example = "cache"))]
    pub source: String,
}

/// Cache statistics response
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(
    title ="Statistics about cached data for an account",
    example = json!({
        "source": "cache",
        "account_id": "507f1f77bcf86cd799439011",
        "stats": {
            "summary": {
                "total_contacts": 150
            },
            "groups": {
                "sales": 50,
                "support": 30,
                "engineering": 70
            }
        }
    })
))]
pub struct CacheStatsResponse {
    /// Source of the statistics (typically "cache")
    pub source: String,

    /// Account ID these statistics belong to
    #[cfg_attr(feature = "openapi", schema(example = "507f1f77bcf86cd799439011"))]
    pub account_id: String,

    /// Nested map of statistics categories and their values
    pub stats: BTreeMap<String, BTreeMap<String, usize>>,
}

/// Pagination parameters for list requests
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(title ="Pagination parameters for list requests"))]
#[serde(rename_all = "camelCase")]
pub struct PaginationParams {
    /// Page number (0-based)
    #[serde(default)]
    #[cfg_attr(feature = "openapi", schema(example = 0, minimum = 0))]
    pub page: u32,

    /// Number of items per page
    #[serde(default = "default_page_size")]
    #[cfg_attr(feature = "openapi", schema(example = 20, minimum = 1, maximum = 100))]
    pub page_size: u32,
}

/// Pagination metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(
    title ="Metadata about pagination",
    example = json!({
        "total": 150,
        "page": 0,
        "pageSize": 20,
        "totalPages": 8,
        "hasNext": true,
        "hasPrevious": false
    })
))]
#[serde(rename_all = "camelCase")]
pub struct PaginationMeta {
    /// Total number of items across all pages
    pub total: u64,

    /// Current page number (0-based)
    pub page: u32,

    /// Number of items per page
    pub page_size: u32,

    /// Total number of pages
    pub total_pages: u32,

    /// Whether there is a next page
    pub has_next: bool,

    /// Whether there is a previous page
    pub has_previous: bool,
}

/// Sort order enumeration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(title ="Sort order direction"))]
#[serde(rename_all = "lowercase")]
pub enum SortOrder {
    /// Ascending order
    #[cfg_attr(feature = "openapi", schema(rename = "asc"))]
    Asc,

    /// Descending order
    #[cfg_attr(feature = "openapi", schema(rename = "desc"))]
    Desc,
}

/// Sorting parameters
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(title ="Sorting parameters for list requests"))]
#[serde(rename_all = "camelCase")]
pub struct SortParams {
    /// Field to sort by
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = "name"))]
    pub sort_by: Option<String>,

    /// Sort order (asc or desc)
    #[serde(default = "default_sort_order")]
    pub sort_order: SortOrder,
}

/// Time range filter
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(title ="Time range filter for queries"))]
#[serde(rename_all = "camelCase")]
pub struct TimeRange {
    /// Start time (inclusive)
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, format = DateTime, example = "2024-01-01T00:00:00Z"))]
    pub start: Option<chrono::DateTime<chrono::Utc>>,

    /// End time (inclusive)
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, format = DateTime, example = "2024-12-31T23:59:59Z"))]
    pub end: Option<chrono::DateTime<chrono::Utc>>,
}

/// API error response
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(
    title ="Standard error response",
    example = json!({
        "code": "VALIDATION_ERROR",
        "message": "Invalid input provided",
        "timestamp": 1704067200
    })
))]
#[serde(rename_all = "camelCase")]
pub struct ApiError {
    /// Error code for programmatic handling
    #[cfg_attr(feature = "openapi", schema(example = "VALIDATION_ERROR"))]
    pub code: String,

    /// Human-readable error message
    #[cfg_attr(feature = "openapi", schema(example = "Invalid email format"))]
    pub message: String,

    /// Additional error details
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<ErrorDetails>,

    /// Request ID for tracking
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = "req_1234567890"))]
    pub request_id: Option<String>,

    /// Unix timestamp when the error occurred
    #[cfg_attr(feature = "openapi", schema(value_type = i64, example = 1704067200))]
    pub timestamp: Option<i64>,
}

/// Detailed error information
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(title ="Additional details about an error"))]
#[serde(rename_all = "camelCase")]
pub struct ErrorDetails {
    /// Specific field that caused the error
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = "email"))]
    pub field: Option<String>,

    /// Reason for the error
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = "Invalid format"))]
    pub reason: Option<String>,

    /// List of validation errors
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub validation_errors: Vec<ValidationError>,
}

/// Validation error details
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(title ="Details about a field validation error"))]
#[serde(rename_all = "camelCase")]
pub struct ValidationError {
    /// Field that failed validation
    #[cfg_attr(feature = "openapi", schema(example = "email"))]
    pub field: String,

    /// Validation error code
    #[cfg_attr(feature = "openapi", schema(example = "format"))]
    pub code: String,

    /// Human-readable validation error message
    #[cfg_attr(feature = "openapi", schema(example = "Email must be a valid email address"))]
    pub message: String,
}

/// Response metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(title ="Metadata about the API response"))]
#[serde(rename_all = "camelCase")]
pub struct ResponseMetadata {
    /// Unique request identifier
    #[cfg_attr(feature = "openapi", schema(example = "req_1234567890"))]
    pub request_id: String,

    /// Timestamp when the response was generated
    #[cfg_attr(feature = "openapi", schema(value_type = String, format = DateTime, example = "2024-01-01T00:00:00Z"))]
    pub timestamp: chrono::DateTime<chrono::Utc>,

    /// API version
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = "1.0.0"))]
    pub version: Option<String>,

    /// Processing time in milliseconds
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = 42))]
    pub processing_time_ms: Option<u64>,
}

/// Search parameters
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(title ="Parameters for search queries"))]
#[serde(rename_all = "camelCase")]
pub struct SearchParams {
    /// Search query string
    #[cfg_attr(feature = "openapi", schema(example = "john doe"))]
    pub query: String,

    /// Fields to search in
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = json!(["name", "email"])))]
    pub fields: Option<Vec<String>>,

    /// Enable fuzzy search
    #[serde(default)]
    #[cfg_attr(feature = "openapi", schema(example = false))]
    pub fuzzy: bool,

    /// Enable search result highlighting
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = true))]
    pub highlight: Option<bool>,
}

/// Filter parameters
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(
    title ="Dynamic filter parameters",
    example = json!({
        "status": "active",
        "category": "premium"
    })
))]
#[serde(rename_all = "camelCase")]
pub struct FilterParams {
    /// Dynamic filters as key-value pairs
    #[serde(flatten)]
    pub filters: serde_json::Map<String, serde_json::Value>,
}

/// Wrapper for consistent ID handling
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(
    title ="ID wrapper for consistent handling",
    value_type = String,
    example = "507f1f77bcf86cd799439011"
))]
pub struct Id(pub String);

/// Combined list request parameters
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(title ="Common parameters for list endpoints"))]
#[serde(rename_all = "camelCase")]
pub struct ListRequest {
    /// Pagination parameters
    #[serde(flatten)]
    pub pagination: PaginationParams,

    /// Sorting parameters
    #[serde(flatten)]
    pub sort: SortParams,

    /// Search parameters
    #[serde(skip_serializing_if = "Option::is_none")]
    pub search: Option<SearchParams>,

    /// Time range filter
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_range: Option<TimeRange>,

    /// Additional filters
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filters: Option<FilterParams>,
}

// Helper functions
fn default_page_size() -> u32 {
    20
}

fn default_sort_order() -> SortOrder {
    SortOrder::Asc
}

// Implementations
impl Default for PaginationParams {
    fn default() -> Self {
        Self {
            page: 0,
            page_size: default_page_size(),
        }
    }
}

impl PaginationParams {
    pub fn new(page: u32, page_size: u32) -> Self {
        Self { page, page_size }
    }

    pub fn offset(&self) -> u64 {
        (self.page as u64) * (self.page_size as u64)
    }

    pub fn limit(&self) -> u64 {
        self.page_size as u64
    }
}

impl PaginationMeta {
    pub fn new(total: u64, page: u32, page_size: u32) -> Self {
        let total_pages = ((total as f64) / (page_size as f64)).ceil() as u32;
        Self {
            total,
            page,
            page_size,
            total_pages,
            has_next: page < total_pages.saturating_sub(1),
            has_previous: page > 0,
        }
    }
}

impl Default for SortOrder {
    fn default() -> Self {
        Self::Asc
    }
}

impl fmt::Display for SortOrder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SortOrder::Asc => write!(f, "asc"),
            SortOrder::Desc => write!(f, "desc"),
        }
    }
}

impl Default for SortParams {
    fn default() -> Self {
        Self {
            sort_by: None,
            sort_order: default_sort_order(),
        }
    }
}

impl ApiError {
    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            message: message.into(),
            details: None,
            request_id: None,
            timestamp: Some(chrono::Utc::now().timestamp()),
        }
    }

    pub fn with_field(mut self, field: impl Into<String>) -> Self {
        self.details = Some(ErrorDetails {
            field: Some(field.into()),
            reason: None,
            validation_errors: Vec::new(),
        });
        self
    }

    pub fn with_request_id(mut self, request_id: impl Into<String>) -> Self {
        self.request_id = Some(request_id.into());
        self
    }
}

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

impl From<String> for Id {
    fn from(s: String) -> Self {
        Id(s)
    }
}

impl From<&str> for Id {
    fn from(s: &str) -> Self {
        Id(s.to_string())
    }
}

impl TimeRange {
    pub fn new(start: Option<chrono::DateTime<chrono::Utc>>, end: Option<chrono::DateTime<chrono::Utc>>) -> Self {
        Self { start, end }
    }

    pub fn is_valid(&self) -> bool {
        match (self.start, self.end) {
            (Some(start), Some(end)) => start <= end,
            _ => true,
        }
    }
}