paladin-ai-core 0.4.2

Pure domain types for the Paladin framework — zero infrastructure dependencies
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
/*
Notification Container Module

Rich domain model for the notification system following Domain-Driven Design principles.
This module contains the core domain entities, value objects, and domain events for notifications.

The notification system is built as an extension of the Message system but provides specialized
domain concepts for notification management, delivery tracking, and content templating.

Domain Concepts:
- Notification: Core aggregate root representing a notification entity
- NotificationContent: Value object for rich content with templates
- NotificationRecipient: Value object for recipient targeting
- NotificationChannel: Enum for delivery channels
- NotificationPriority: Priority levels for delivery
- NotificationStatus: Delivery status tracking
- NotificationTemplate: Template management for content generation
- NotificationEvent: Domain events for notification lifecycle

The notification domain follows hexagonal architecture principles with clear boundaries
between domain logic and external concerns.
*/

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
use thiserror::Error;
use uuid::Uuid;

use crate::base::entity::message::{Location, Message, MessagePriority};

/// Result type for notification domain operations
pub type NotificationResult<T> = Result<T, NotificationDomainError>;

/// Domain errors for notification operations
#[derive(Debug, Clone, Error, PartialEq)]
pub enum NotificationDomainError {
    #[error("Invalid recipient: {0}")]
    InvalidRecipient(String),

    #[error("Invalid content: {0}")]
    InvalidContent(String),

    #[error("Template not found: {0}")]
    TemplateNotFound(String),

    #[error("Template rendering failed: {0}")]
    TemplateRenderingFailed(String),

    #[error("Notification expired")]
    NotificationExpired,

    #[error("Invalid notification state transition from {from} to {to}")]
    InvalidStateTransition { from: String, to: String },

    #[error("Notification already processed")]
    NotificationAlreadyProcessed,

    #[error("Validation error: {0}")]
    ValidationError(String),
}

/// Notification priority levels for delivery ordering
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Default,
)]
pub enum NotificationPriority {
    Low = 0,
    #[default]
    Normal = 1,
    High = 2,
    Critical = 3,
    Emergency = 4,
}

impl From<NotificationPriority> for MessagePriority {
    fn from(priority: NotificationPriority) -> Self {
        match priority {
            NotificationPriority::Low => MessagePriority::Low,
            NotificationPriority::Normal => MessagePriority::Normal,
            NotificationPriority::High => MessagePriority::High,
            NotificationPriority::Critical | NotificationPriority::Emergency => {
                MessagePriority::Critical
            }
        }
    }
}

/// Delivery channels for notifications
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum NotificationChannel {
    Email,
    Sms,
    Push,
    WebPush,
    Webhook,
    InApp,
    System,
    Slack,
    Discord,
    Teams,
    Custom(String),
}

impl fmt::Display for NotificationChannel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            NotificationChannel::Email => write!(f, "email"),
            NotificationChannel::Sms => write!(f, "sms"),
            NotificationChannel::Push => write!(f, "push"),
            NotificationChannel::WebPush => write!(f, "webpush"),
            NotificationChannel::Webhook => write!(f, "webhook"),
            NotificationChannel::InApp => write!(f, "inapp"),
            NotificationChannel::System => write!(f, "system"),
            NotificationChannel::Slack => write!(f, "slack"),
            NotificationChannel::Discord => write!(f, "discord"),
            NotificationChannel::Teams => write!(f, "teams"),
            NotificationChannel::Custom(name) => write!(f, "custom:{}", name),
        }
    }
}

/// Notification delivery status
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum NotificationStatus {
    Draft,
    Pending,
    Queued,
    Sending,
    Sent,
    Delivered,
    Read,
    Failed,
    Cancelled,
    Expired,
    Retry(u32),
}

impl NotificationStatus {
    /// Check if the notification is in a final state
    pub fn is_final(&self) -> bool {
        matches!(
            self,
            NotificationStatus::Delivered
                | NotificationStatus::Read
                | NotificationStatus::Failed
                | NotificationStatus::Cancelled
                | NotificationStatus::Expired
        )
    }

    /// Check if the notification can be retried
    pub fn can_retry(&self) -> bool {
        matches!(
            self,
            NotificationStatus::Failed | NotificationStatus::Retry(_)
        )
    }

    /// Get the next retry status
    pub fn next_retry(&self, max_retries: u32) -> Option<NotificationStatus> {
        match self {
            NotificationStatus::Failed => Some(NotificationStatus::Retry(1)),
            NotificationStatus::Retry(count) if *count < max_retries => {
                Some(NotificationStatus::Retry(count + 1))
            }
            _ => None,
        }
    }
}

/// Recipient information for notifications
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum NotificationRecipient {
    Email(String),
    Phone(String),
    UserId(String),
    DeviceToken(String),
    WebhookUrl(String),
    SystemComponent(String),
    Multiple(Vec<NotificationRecipient>),
}

impl NotificationRecipient {
    /// Validate the recipient format
    pub fn validate(&self) -> NotificationResult<()> {
        match self {
            NotificationRecipient::Email(email) => {
                if email.contains('@') && email.len() > 3 {
                    Ok(())
                } else {
                    Err(NotificationDomainError::InvalidRecipient(format!(
                        "Invalid email format: {}",
                        email
                    )))
                }
            }
            NotificationRecipient::Phone(phone) => {
                if phone.len() >= 10 {
                    Ok(())
                } else {
                    Err(NotificationDomainError::InvalidRecipient(format!(
                        "Invalid phone format: {}",
                        phone
                    )))
                }
            }
            NotificationRecipient::UserId(id) => {
                if !id.is_empty() {
                    Ok(())
                } else {
                    Err(NotificationDomainError::InvalidRecipient(
                        "User ID cannot be empty".to_string(),
                    ))
                }
            }
            NotificationRecipient::Multiple(recipients) => {
                for recipient in recipients {
                    recipient.validate()?;
                }
                Ok(())
            }
            _ => Ok(()), // Other types are assumed valid for now
        }
    }

    /// Get the primary identifier for the recipient
    pub fn identifier(&self) -> String {
        match self {
            NotificationRecipient::Email(email) => email.clone(),
            NotificationRecipient::Phone(phone) => phone.clone(),
            NotificationRecipient::UserId(id) => id.clone(),
            NotificationRecipient::DeviceToken(token) => token.clone(),
            NotificationRecipient::WebhookUrl(url) => url.clone(),
            NotificationRecipient::SystemComponent(component) => component.clone(),
            NotificationRecipient::Multiple(recipients) => {
                format!("multiple:{}", recipients.len())
            }
        }
    }

    /// Get the compatible channels for this recipient type
    pub fn compatible_channels(&self) -> Vec<NotificationChannel> {
        match self {
            NotificationRecipient::Email(_) => vec![NotificationChannel::Email],
            NotificationRecipient::Phone(_) => vec![NotificationChannel::Sms],
            NotificationRecipient::UserId(_) => vec![
                NotificationChannel::Email,
                NotificationChannel::Push,
                NotificationChannel::InApp,
            ],
            NotificationRecipient::DeviceToken(_) => {
                vec![NotificationChannel::Push, NotificationChannel::WebPush]
            }
            NotificationRecipient::WebhookUrl(_) => vec![NotificationChannel::Webhook],
            NotificationRecipient::SystemComponent(_) => vec![NotificationChannel::System],
            NotificationRecipient::Multiple(_) => vec![], // Determined by individual recipients
        }
    }
}

/// Rich content for notifications with template support
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NotificationContent {
    pub title: String,
    pub body: String,
    pub category: String,
    pub action_url: Option<String>,
    pub attachments: Vec<NotificationAttachment>,
    pub template_id: Option<String>,
    pub template_variables: HashMap<String, serde_json::Value>,
    pub metadata: HashMap<String, serde_json::Value>,
}

impl NotificationContent {
    /// Create new notification content
    pub fn new(title: String, body: String, category: String) -> Self {
        Self {
            title,
            body,
            category,
            action_url: None,
            attachments: Vec::new(),
            template_id: None,
            template_variables: HashMap::new(),
            metadata: HashMap::new(),
        }
    }

    /// Create content with template
    pub fn with_template(
        template_id: String,
        variables: HashMap<String, serde_json::Value>,
        category: String,
    ) -> Self {
        Self {
            title: String::new(), // Will be filled by template
            body: String::new(),  // Will be filled by template
            category,
            action_url: None,
            attachments: Vec::new(),
            template_id: Some(template_id),
            template_variables: variables,
            metadata: HashMap::new(),
        }
    }

    /// Validate the content
    pub fn validate(&self) -> NotificationResult<()> {
        if self.title.is_empty() && self.template_id.is_none() {
            return Err(NotificationDomainError::InvalidContent(
                "Title cannot be empty when no template is specified".to_string(),
            ));
        }

        if self.body.is_empty() && self.template_id.is_none() {
            return Err(NotificationDomainError::InvalidContent(
                "Body cannot be empty when no template is specified".to_string(),
            ));
        }

        if self.category.is_empty() {
            return Err(NotificationDomainError::InvalidContent(
                "Category cannot be empty".to_string(),
            ));
        }

        Ok(())
    }

    /// Check if this content uses a template
    pub fn uses_template(&self) -> bool {
        self.template_id.is_some()
    }

    /// Add attachment
    pub fn add_attachment(&mut self, attachment: NotificationAttachment) {
        self.attachments.push(attachment);
    }

    /// Add template variable
    pub fn add_variable<T: serde::Serialize>(
        &mut self,
        key: String,
        value: T,
    ) -> NotificationResult<()> {
        let json_value = serde_json::to_value(value)
            .map_err(|e| NotificationDomainError::ValidationError(e.to_string()))?;
        self.template_variables.insert(key, json_value);
        Ok(())
    }
}

/// Attachment for notifications
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NotificationAttachment {
    pub filename: String,
    pub content_type: String,
    pub data: Vec<u8>,
    pub size: usize,
}

impl NotificationAttachment {
    /// Create new attachment
    pub fn new(filename: String, content_type: String, data: Vec<u8>) -> Self {
        let size = data.len();
        Self {
            filename,
            content_type,
            data,
            size,
        }
    }

    /// Validate attachment
    pub fn validate(&self, max_size: usize) -> NotificationResult<()> {
        if self.filename.is_empty() {
            return Err(NotificationDomainError::InvalidContent(
                "Attachment filename cannot be empty".to_string(),
            ));
        }

        if self.size > max_size {
            return Err(NotificationDomainError::InvalidContent(format!(
                "Attachment size {} exceeds maximum {}",
                self.size, max_size
            )));
        }

        Ok(())
    }
}

/// Template for notification content generation
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NotificationTemplate {
    pub id: String,
    pub name: String,
    pub channel: NotificationChannel,
    pub subject_template: Option<String>,
    pub body_template: String,
    pub variables: Vec<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub version: u32,
    pub is_active: bool,
}

impl NotificationTemplate {
    /// Create new template
    pub fn new(
        id: String,
        name: String,
        channel: NotificationChannel,
        body_template: String,
        variables: Vec<String>,
    ) -> Self {
        let now = Utc::now();
        Self {
            id,
            name,
            channel,
            subject_template: None,
            body_template,
            variables,
            created_at: now,
            updated_at: now,
            version: 1,
            is_active: true,
        }
    }

    /// Validate template
    pub fn validate(&self) -> NotificationResult<()> {
        if self.id.is_empty() {
            return Err(NotificationDomainError::ValidationError(
                "Template ID cannot be empty".to_string(),
            ));
        }

        if self.name.is_empty() {
            return Err(NotificationDomainError::ValidationError(
                "Template name cannot be empty".to_string(),
            ));
        }

        if self.body_template.is_empty() {
            return Err(NotificationDomainError::ValidationError(
                "Template body cannot be empty".to_string(),
            ));
        }

        Ok(())
    }

    /// Update template
    pub fn update(&mut self, body_template: String, variables: Vec<String>) {
        self.body_template = body_template;
        self.variables = variables;
        self.updated_at = Utc::now();
        self.version += 1;
    }

    /// Deactivate template
    pub fn deactivate(&mut self) {
        self.is_active = false;
        self.updated_at = Utc::now();
    }
}

/// Core notification aggregate root
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Notification {
    pub id: Uuid,
    pub recipient: NotificationRecipient,
    pub content: NotificationContent,
    pub channel: NotificationChannel,
    pub priority: NotificationPriority,
    pub status: NotificationStatus,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub scheduled_time: Option<DateTime<Utc>>,
    pub expiry_time: Option<DateTime<Utc>>,
    pub sent_at: Option<DateTime<Utc>>,
    pub delivered_at: Option<DateTime<Utc>>,
    pub read_at: Option<DateTime<Utc>>,
    pub retry_count: u32,
    pub max_retries: u32,
    pub external_id: Option<String>,
    pub correlation_id: Option<Uuid>,
    pub metadata: HashMap<String, serde_json::Value>,
}

impl Notification {
    /// Create new notification
    pub fn new(
        recipient: NotificationRecipient,
        content: NotificationContent,
        channel: NotificationChannel,
        priority: NotificationPriority,
    ) -> NotificationResult<Self> {
        // Validate inputs
        recipient.validate()?;
        content.validate()?;

        // Validate channel compatibility
        if !recipient.compatible_channels().is_empty()
            && !recipient.compatible_channels().contains(&channel)
        {
            return Err(NotificationDomainError::InvalidRecipient(format!(
                "Channel {:?} not compatible with recipient type",
                channel
            )));
        }

        let now = Utc::now();
        Ok(Self {
            id: Uuid::new_v4(),
            recipient,
            content,
            channel,
            priority,
            status: NotificationStatus::Draft,
            created_at: now,
            updated_at: now,
            scheduled_time: None,
            expiry_time: None,
            sent_at: None,
            delivered_at: None,
            read_at: None,
            retry_count: 0,
            max_retries: 3,
            external_id: None,
            correlation_id: None,
            metadata: HashMap::new(),
        })
    }

    /// Schedule notification for future delivery
    pub fn schedule(&mut self, scheduled_time: DateTime<Utc>) -> NotificationResult<()> {
        if scheduled_time <= Utc::now() {
            return Err(NotificationDomainError::ValidationError(
                "Scheduled time must be in the future".to_string(),
            ));
        }

        self.scheduled_time = Some(scheduled_time);
        self.update_status(NotificationStatus::Pending)?;
        Ok(())
    }

    /// Set expiry time
    pub fn set_expiry(&mut self, expiry_time: DateTime<Utc>) -> NotificationResult<()> {
        if expiry_time <= Utc::now() {
            return Err(NotificationDomainError::ValidationError(
                "Expiry time must be in the future".to_string(),
            ));
        }

        self.expiry_time = Some(expiry_time);
        self.updated_at = Utc::now();
        Ok(())
    }

    /// Update notification status
    pub fn update_status(&mut self, new_status: NotificationStatus) -> NotificationResult<()> {
        // Validate state transition
        if !self.can_transition_to(&new_status) {
            return Err(NotificationDomainError::InvalidStateTransition {
                from: format!("{:?}", self.status),
                to: format!("{:?}", new_status),
            });
        }

        let _old_status = self.status.clone();
        self.status = new_status;
        self.updated_at = Utc::now();

        // Update timestamps based on status
        match &self.status {
            NotificationStatus::Sent => {
                self.sent_at = Some(Utc::now());
            }
            NotificationStatus::Delivered => {
                if self.sent_at.is_none() {
                    self.sent_at = Some(Utc::now());
                }
                self.delivered_at = Some(Utc::now());
            }
            NotificationStatus::Read => {
                if self.delivered_at.is_none() {
                    self.delivered_at = Some(Utc::now());
                }
                self.read_at = Some(Utc::now());
            }
            NotificationStatus::Retry(count) => {
                self.retry_count = *count;
            }
            _ => {}
        }

        Ok(())
    }

    /// Check if notification can transition to new status
    fn can_transition_to(&self, new_status: &NotificationStatus) -> bool {
        use NotificationStatus::*;

        match (&self.status, new_status) {
            // From Draft
            (Draft, Pending | Queued | Cancelled) => true,

            // From Pending
            (Pending, Queued | Cancelled | Expired) => true,

            // From Queued
            (Queued, Sending | Cancelled | Expired) => true,

            // From Sending
            (Sending, Sent | Failed | Cancelled) => true,

            // From Sent
            (Sent, Delivered | Failed) => true,

            // From Delivered
            (Delivered, Read) => true,

            // From Failed
            (Failed, Retry(_) | Cancelled) => true,

            // From Retry
            (Retry(_), Sending | Failed | Cancelled) => true,

            // Final states cannot transition
            (Cancelled | Expired | Read, _) => false,

            // Same status is allowed
            (status1, status2) if status1 == status2 => true,

            _ => false,
        }
    }

    /// Check if notification is expired
    pub fn is_expired(&self) -> bool {
        if let Some(expiry) = self.expiry_time {
            Utc::now() > expiry
        } else {
            false
        }
    }

    /// Check if notification should be sent now
    pub fn should_send_now(&self) -> bool {
        if self.is_expired() {
            return false;
        }

        match self.scheduled_time {
            Some(scheduled) => Utc::now() >= scheduled,
            None => matches!(self.status, NotificationStatus::Queued),
        }
    }

    /// Check if notification can be retried
    pub fn can_retry(&self) -> bool {
        self.status.can_retry() && self.retry_count < self.max_retries && !self.is_expired()
    }

    /// Convert to message for delivery
    pub fn to_message(
        &self,
        source: Location,
        destination: Location,
    ) -> Message<NotificationContent> {
        Message::complete(
            source,
            destination,
            self.content.clone(),
            self.priority.into(),
            self.correlation_id,
        )
    }

    /// Add metadata
    pub fn add_metadata<T: serde::Serialize>(
        &mut self,
        key: String,
        value: T,
    ) -> NotificationResult<()> {
        let json_value = serde_json::to_value(value)
            .map_err(|e| NotificationDomainError::ValidationError(e.to_string()))?;
        self.metadata.insert(key, json_value);
        self.updated_at = Utc::now();
        Ok(())
    }
}

/// Domain events for notification lifecycle
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum NotificationEvent {
    NotificationCreated {
        notification_id: Uuid,
        recipient: NotificationRecipient,
        channel: NotificationChannel,
        priority: NotificationPriority,
        created_at: DateTime<Utc>,
    },
    NotificationScheduled {
        notification_id: Uuid,
        scheduled_time: DateTime<Utc>,
        scheduled_at: DateTime<Utc>,
    },
    NotificationQueued {
        notification_id: Uuid,
        channel: NotificationChannel,
        queued_at: DateTime<Utc>,
    },
    NotificationSent {
        notification_id: Uuid,
        channel: NotificationChannel,
        external_id: Option<String>,
        sent_at: DateTime<Utc>,
    },
    NotificationDelivered {
        notification_id: Uuid,
        delivered_at: DateTime<Utc>,
    },
    NotificationRead {
        notification_id: Uuid,
        read_at: DateTime<Utc>,
    },
    NotificationFailed {
        notification_id: Uuid,
        error: String,
        retry_count: u32,
        failed_at: DateTime<Utc>,
    },
    NotificationCancelled {
        notification_id: Uuid,
        reason: Option<String>,
        cancelled_at: DateTime<Utc>,
    },
    NotificationExpired {
        notification_id: Uuid,
        expired_at: DateTime<Utc>,
    },
}

impl NotificationEvent {
    /// Get the notification ID for this event
    pub fn notification_id(&self) -> Uuid {
        match self {
            NotificationEvent::NotificationCreated {
                notification_id, ..
            }
            | NotificationEvent::NotificationScheduled {
                notification_id, ..
            }
            | NotificationEvent::NotificationQueued {
                notification_id, ..
            }
            | NotificationEvent::NotificationSent {
                notification_id, ..
            }
            | NotificationEvent::NotificationDelivered {
                notification_id, ..
            }
            | NotificationEvent::NotificationRead {
                notification_id, ..
            }
            | NotificationEvent::NotificationFailed {
                notification_id, ..
            }
            | NotificationEvent::NotificationCancelled {
                notification_id, ..
            }
            | NotificationEvent::NotificationExpired {
                notification_id, ..
            } => *notification_id,
        }
    }

    /// Get the event timestamp
    pub fn timestamp(&self) -> DateTime<Utc> {
        match self {
            NotificationEvent::NotificationCreated { created_at, .. } => *created_at,
            NotificationEvent::NotificationScheduled { scheduled_at, .. } => *scheduled_at,
            NotificationEvent::NotificationQueued { queued_at, .. } => *queued_at,
            NotificationEvent::NotificationSent { sent_at, .. } => *sent_at,
            NotificationEvent::NotificationDelivered { delivered_at, .. } => *delivered_at,
            NotificationEvent::NotificationRead { read_at, .. } => *read_at,
            NotificationEvent::NotificationFailed { failed_at, .. } => *failed_at,
            NotificationEvent::NotificationCancelled { cancelled_at, .. } => *cancelled_at,
            NotificationEvent::NotificationExpired { expired_at, .. } => *expired_at,
        }
    }
}

/// Statistics for notification service orchestration operations.
///
/// Plain data type with no port fields — suitable for core container layer.
#[derive(Debug, Clone, Default)]
pub struct NotificationServiceStats {
    /// Total notifications created
    pub notifications_created: u64,
    /// Total notifications sent
    pub notifications_sent: u64,
    /// Total notifications delivered
    pub notifications_delivered: u64,
    /// Total notifications failed
    pub notifications_failed: u64,
    /// Notifications by channel
    pub channel_stats: HashMap<NotificationChannel, u64>,
    /// Notifications by priority
    pub priority_stats: HashMap<NotificationPriority, u64>,
    /// Average delivery time in milliseconds
    pub avg_delivery_time_ms: Option<u64>,
    /// Last activity timestamp
    pub last_activity: Option<DateTime<Utc>>,
    /// Active notifications count
    pub active_notifications: u64,
}

/// Configuration for the notification orchestrator.
///
/// Plain config struct with `Default` impl and no port references.
#[derive(Debug, Clone)]
pub struct NotificationServiceConfig {
    /// Default maximum retries for failed notifications
    pub default_max_retries: u32,
    /// Default expiry time for notifications in seconds
    pub default_expiry_seconds: i64,
    /// Enable notification persistence
    pub enable_persistence: bool,
    /// Maximum notifications to process per batch
    pub batch_size: usize,
    /// Processing interval in milliseconds
    pub processing_interval_ms: u64,
    /// Template cache size
    pub template_cache_size: usize,
    /// Maximum attachment size in bytes
    pub max_attachment_size: usize,
}

impl Default for NotificationServiceConfig {
    fn default() -> Self {
        Self {
            default_max_retries: 3,
            default_expiry_seconds: 86400, // 24 hours
            enable_persistence: true,
            batch_size: 100,
            processing_interval_ms: 1000,
            template_cache_size: 1000,
            max_attachment_size: 25 * 1024 * 1024, // 25MB
        }
    }
}

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

    #[test]
    fn test_notification_creation() {
        let recipient = NotificationRecipient::Email("test@example.com".to_string());
        let content = NotificationContent::new(
            "Test Title".to_string(),
            "Test Body".to_string(),
            "test".to_string(),
        );

        let notification = Notification::new(
            recipient,
            content,
            NotificationChannel::Email,
            NotificationPriority::Normal,
        );

        assert!(notification.is_ok());
        let notification = notification.unwrap();
        assert_eq!(notification.status, NotificationStatus::Draft);
        assert_eq!(notification.retry_count, 0);
    }

    #[test]
    fn test_notification_status_transitions() {
        let recipient = NotificationRecipient::Email("test@example.com".to_string());
        let content =
            NotificationContent::new("Test".to_string(), "Test".to_string(), "test".to_string());

        let mut notification = Notification::new(
            recipient,
            content,
            NotificationChannel::Email,
            NotificationPriority::Normal,
        )
        .unwrap();

        // Valid transition
        assert!(
            notification
                .update_status(NotificationStatus::Pending)
                .is_ok()
        );
        assert_eq!(notification.status, NotificationStatus::Pending);

        // Invalid transition
        assert!(
            notification
                .update_status(NotificationStatus::Read)
                .is_err()
        );
    }

    #[test]
    fn test_recipient_validation() {
        let valid_email = NotificationRecipient::Email("test@example.com".to_string());
        assert!(valid_email.validate().is_ok());

        let invalid_email = NotificationRecipient::Email("invalid".to_string());
        assert!(invalid_email.validate().is_err());
    }

    #[test]
    fn test_notification_template() {
        let template = NotificationTemplate::new(
            "test-template".to_string(),
            "Test Template".to_string(),
            NotificationChannel::Email,
            "Hello {{name}}!".to_string(),
            vec!["name".to_string()],
        );

        assert!(template.validate().is_ok());
        assert_eq!(template.version, 1);
        assert!(template.is_active);
    }

    #[test]
    fn test_notification_expiry() {
        let recipient = NotificationRecipient::Email("test@example.com".to_string());
        let content =
            NotificationContent::new("Test".to_string(), "Test".to_string(), "test".to_string());

        let mut notification = Notification::new(
            recipient,
            content,
            NotificationChannel::Email,
            NotificationPriority::Normal,
        )
        .unwrap();

        // Set expiry in the past
        let past_time = Utc::now() - chrono::Duration::hours(1);
        notification.expiry_time = Some(past_time);

        assert!(notification.is_expired());
        assert!(!notification.should_send_now());
    }

    #[test]
    fn test_notification_service_stats_default() {
        let stats = NotificationServiceStats::default();
        assert_eq!(stats.notifications_created, 0);
        assert_eq!(stats.notifications_sent, 0);
        assert_eq!(stats.active_notifications, 0);
        assert!(stats.channel_stats.is_empty());
        assert!(stats.priority_stats.is_empty());
        assert!(stats.avg_delivery_time_ms.is_none());
        assert!(stats.last_activity.is_none());
    }

    #[test]
    fn test_notification_service_config_default() {
        let config = NotificationServiceConfig::default();
        assert_eq!(config.default_max_retries, 3);
        assert_eq!(config.default_expiry_seconds, 86400);
        assert!(config.enable_persistence);
        assert_eq!(config.batch_size, 100);
        assert_eq!(config.processing_interval_ms, 1000);
        assert_eq!(config.template_cache_size, 1000);
        assert_eq!(config.max_attachment_size, 25 * 1024 * 1024);
    }
}