1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
//! Notification Ports - Multi-Channel Notification Delivery Abstraction
//!
//! This module defines the output ports (interfaces) for the notification system following
//! Hexagonal Architecture principles. These ports provide clean abstractions that allow
//! the application layer to interact with external notification delivery mechanisms
//! (email, SMS, push notifications, webhooks, Slack, etc.) without being coupled to
//! their implementation details.
//!
//! # Purpose
//!
//! Notification ports enable Paladin agents to communicate with users and external systems
//! through multiple channels while maintaining a clean separation between the core business
//! logic and the specific notification delivery mechanisms. This allows you to:
//!
//! - Send notifications through multiple channels (email, SMS, push, webhooks, Slack)
//! - Switch between notification providers without changing application code
//! - Test notification logic without sending real messages
//! - Implement retry logic and failure handling consistently
//! - Track delivery status and statistics across all channels
//! - Use templates for consistent message formatting
//!
//! # Hexagonal Architecture (Ports & Adapters)
//!
//! ```text
//! ┌──────────────────────────────────────────────────────────────┐
//! │ Application Layer │
//! │ ┌────────────────────────────────────────────────────────┐ │
//! │ │ Paladin Agent Execution │ │
//! │ │ - Send alerts on task completion │ │
//! │ │ - Notify users of errors │ │
//! │ │ - Deliver reports via email │ │
//! │ └─────────────────────┬────────────────────────────────────┘ │
//! │ │ │
//! │ ↓ │
//! │ ┌────────────────────────────────────────────────────────┐ │
//! │ │ NotificationDeliveryPort (trait) │ │
//! │ │ NotificationTemplatePort (trait) │ │
//! │ │ - deliver_notification() │ │
//! │ │ - render_template() │ │
//! │ └────────────────────┬───────────────────────────────────┘ │
//! └─────────────────────────┼────────────────────────────────────┘
//! │
//! ┌───────────────┼───────────────┐
//! │ │ │
//! ↓ ↓ ↓
//! ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
//! │ Email │ │ SMS │ │ Slack │
//! │ Adapter │ │ Adapter │ │ Adapter │
//! │ (SMTP) │ │ (Twilio) │ │ (Webhook) │
//! └─────────────┘ └─────────────┘ └─────────────┘
//! ```
//!
//! # Port Segregation (Interface Segregation Principle)
//!
//! The notification system is split into focused interfaces:
//!
//! - **NotificationDeliveryPort**: Core delivery functionality for sending notifications
//! - **NotificationTemplatePort**: Template management and content rendering
//! - **BasicNotificationPort**: Simplified interface combining delivery with basic operations
//!
//! Each port defines a focused interface that can be implemented independently,
//! allowing for flexible adapter implementations and better testability.
//!
//! # Common Use Cases
//!
//! ## 1. Send Email Notification
//!
//! ```ignore
//! use paladin::application::ports::output::notification_port::{
//! NotificationDeliveryPort, NotificationPortError
//! };
//! use paladin::core::platform::container::notification::{
//! Notification, NotificationChannel, NotificationContent,
//! NotificationRecipient, NotificationPriority
//! };
//! use std::sync::Arc;
//!
//! async fn send_task_completion_email(
//! notification_port: Arc<dyn NotificationDeliveryPort>,
//! ) -> Result<(), NotificationPortError> {
//! let notification = Notification::builder()
//! .recipient(NotificationRecipient::email("user@example.com"))
//! .channel(NotificationChannel::Email)
//! .priority(NotificationPriority::Normal)
//! .content(NotificationContent::text(
//! "Task Complete",
//! "Your Paladin task has finished successfully."
//! ))
//! .build()?;
//!
//! let result = notification_port.deliver_notification(notification).await?;
//! println!("Email sent: {:?}", result.status);
//! Ok(())
//! }
//! ```
//!
//! ## 2. Send Bulk Notifications
//!
//! ```ignore
//! use paladin::application::ports::output::notification_port::{
//! NotificationDeliveryPort, BulkDeliveryResult
//! };
//! use paladin::core::platform::container::notification::{
//! Notification, NotificationChannel
//! };
//! use std::sync::Arc;
//!
//! async fn send_bulk_alerts(
//! notification_port: Arc<dyn NotificationDeliveryPort>,
//! users: Vec<String>,
//! message: String,
//! ) -> Result<BulkDeliveryResult, Box<dyn std::error::Error>> {
//! let notifications: Vec<Notification> = users
//! .iter()
//! .map(|email| {
//! Notification::builder()
//! .recipient(NotificationRecipient::email(email))
//! .channel(NotificationChannel::Email)
//! .content(NotificationContent::text("Alert", &message))
//! .build()
//! })
//! .collect::<Result<Vec<_>, _>>()?;
//!
//! let result = notification_port.deliver_bulk(notifications).await?;
//! println!("Sent {}/{} notifications", result.success_count, result.total_count);
//! Ok(result)
//! }
//! ```
//!
//! ## 3. Use Template for Consistent Formatting
//!
//! ```ignore
//! use paladin::application::ports::output::notification_port::{
//! NotificationTemplatePort, NotificationPortError
//! };
//! use paladin::core::platform::container::notification::{
//! NotificationTemplate, NotificationChannel
//! };
//! use std::collections::HashMap;
//! use std::sync::Arc;
//!
//! async fn send_templated_notification(
//! template_port: Arc<dyn NotificationTemplatePort>,
//! ) -> Result<(), NotificationPortError> {
//! // Render template with variables
//! let mut variables = HashMap::new();
//! variables.insert("user_name".to_string(), serde_json::json!("Alice"));
//! variables.insert("task_name".to_string(), serde_json::json!("Data Analysis"));
//! variables.insert("duration".to_string(), serde_json::json!("2 hours"));
//!
//! let content = template_port
//! .render_template("task_completion_email", variables)
//! .await?;
//!
//! println!("Rendered: {} - {}", content.subject, content.body);
//! Ok(())
//! }
//! ```
//!
//! ## 4. Multi-Channel Notification with Fallback
//!
//! ```ignore
//! use paladin::application::ports::output::notification_port::{
//! NotificationDeliveryPort, NotificationPortError
//! };
//! use paladin::core::platform::container::notification::{
//! Notification, NotificationChannel, NotificationStatus
//! };
//! use std::sync::Arc;
//!
//! async fn send_with_fallback(
//! primary: Arc<dyn NotificationDeliveryPort>,
//! fallback: Arc<dyn NotificationDeliveryPort>,
//! notification: Notification,
//! ) -> Result<(), NotificationPortError> {
//! match primary.deliver_notification(notification.clone()).await {
//! Ok(result) if result.status == NotificationStatus::Delivered => {
//! println!("Delivered via primary channel");
//! Ok(())
//! }
//! _ => {
//! println!("Primary failed, trying fallback...");
//! fallback.deliver_notification(notification).await?;
//! Ok(())
//! }
//! }
//! }
//! ```
//!
//! # Channel Support
//!
//! Different adapters support different notification channels:
//!
//! | Channel | Use Case | Typical Adapter |
//! |---------|----------|----------------|
//! | Email | Reports, alerts, receipts | SMTP, SendGrid, AWS SES |
//! | SMS | Urgent alerts, 2FA codes | Twilio, AWS SNS, Nexmo |
//! | Push | Mobile app notifications | FCM, APNs, OneSignal |
//! | Webhook | System-to-system | HTTP client |
//! | Slack | Team collaboration | Slack API, webhooks |
//! | InApp | Application notifications | Database storage |
//!
//! # Error Handling & Retryability
//!
//! NotificationPortError variants indicate whether operations should be retried:
//!
//! | Error | Retryable? | Recovery Strategy |
//! |-------|------------|-------------------|
//! | DeliveryFailed | Maybe | Check error message, implement exponential backoff |
//! | TemplateError | No | Fix template syntax |
//! | StorageError | Yes | Retry with exponential backoff |
//! | ConnectionError | Yes | Retry, check network/DNS |
//! | AuthenticationError | No | Fix credentials in configuration |
//! | RateLimitExceeded | Yes | Wait and retry, implement rate limiting |
//! | ServiceUnavailable | Yes | Exponential backoff, circuit breaker |
//! | ConfigurationError | No | Fix configuration |
//! | ValidationError | No | Fix notification data |
//! | Timeout | Yes | Retry with longer timeout |
//!
//! ## Retry Pattern Example
//!
//! ```ignore
//! use paladin::application::ports::output::notification_port::{
//! NotificationDeliveryPort, NotificationPortError
//! };
//! use paladin::core::platform::container::notification::Notification;
//! use std::sync::Arc;
//! use std::time::Duration;
//! use tokio::time::sleep;
//!
//! async fn deliver_with_retry(
//! port: Arc<dyn NotificationDeliveryPort>,
//! notification: Notification,
//! max_retries: u32,
//! ) -> Result<(), NotificationPortError> {
//! let mut attempts = 0;
//! let mut backoff = Duration::from_millis(100);
//!
//! loop {
//! match port.deliver_notification(notification.clone()).await {
//! Ok(result) => return Ok(()),
//! Err(e) if attempts >= max_retries => return Err(e),
//! Err(NotificationPortError::RateLimitExceeded) => {
//! sleep(backoff).await;
//! backoff *= 2;
//! }
//! Err(NotificationPortError::ServiceUnavailable(_)) => {
//! sleep(backoff).await;
//! backoff *= 2;
//! }
//! Err(e) => return Err(e), // Non-retryable error
//! }
//! attempts += 1;
//! }
//! }
//! ```
//!
//! # Thread Safety
//!
//! All notification ports are `Send + Sync`, allowing safe use across async task boundaries.
//! This is critical for Paladin's concurrent agent execution model where multiple agents
//! may send notifications simultaneously.
//!
//! # Implementation Notes
//!
//! ## Adapter Implementation Checklist
//!
//! When implementing a notification adapter:
//!
//! 1. **Channel Handling**: Implement `can_handle()` to filter notifications by channel
//! 2. **Capabilities**: Return accurate `DeliveryCapabilities` to inform callers of limits
//! 3. **Error Mapping**: Map provider errors to appropriate `NotificationPortError` variants
//! 4. **Idempotency**: Handle duplicate deliveries gracefully (check external_id)
//! 5. **Timeouts**: Set reasonable timeouts for external API calls
//! 6. **Health Checks**: Implement `health_check()` for monitoring/circuit breakers
//! 7. **Metrics**: Track delivery success/failure rates, latency
//! 8. **Logging**: Log delivery attempts, failures, external IDs for tracing
//!
//! ## Performance Considerations
//!
//! - **Connection Pooling**: Reuse HTTP/SMTP connections across deliveries
//! - **Bulk Delivery**: Implement native bulk APIs when supported (SendGrid, Twilio)
//! - **Async I/O**: Use non-blocking I/O for all external calls
//! - **Circuit Breaker**: Stop sending to failing providers temporarily
//! - **Queue Integration**: Use QueuePort for async delivery to prevent blocking agents
//!
//! ## Testing Strategy
//!
//! ```ignore
//! use paladin::application::ports::output::notification_port::{
//! NotificationDeliveryPort, NotificationDeliveryResult,
//! NotificationPortError, DeliveryCapabilities
//! };
//! use paladin::core::platform::container::notification::{
//! Notification, NotificationChannel, NotificationStatus
//! };
//! use async_trait::async_trait;
//!
//! /// Mock notification port for testing
//! struct MockNotificationPort {
//! should_fail: bool,
//! }
//!
//! #[async_trait]
//! impl NotificationDeliveryPort for MockNotificationPort {
//! fn channel(&self) -> NotificationChannel {
//! NotificationChannel::Email
//! }
//!
//! fn can_handle(&self, notification: &Notification) -> bool {
//! notification.channel == NotificationChannel::Email
//! }
//!
//! async fn deliver_notification(
//! &self,
//! notification: Notification,
//! ) -> Result<NotificationDeliveryResult, NotificationPortError> {
//! if self.should_fail {
//! Err(NotificationPortError::DeliveryFailed("Mock failure".into()))
//! } else {
//! Ok(NotificationDeliveryResult {
//! notification_id: notification.id,
//! status: NotificationStatus::Delivered,
//! external_id: Some("mock-123".into()),
//! processing_time_ms: 10,
//! error_message: None,
//! delivered_at: chrono::Utc::now(),
//! channel: NotificationChannel::Email,
//! metadata: Default::default(),
//! })
//! }
//! }
//!
//! async fn health_check(&self) -> bool {
//! !self.should_fail
//! }
//!
//! fn capabilities(&self) -> DeliveryCapabilities {
//! DeliveryCapabilities {
//! supports_bulk: false,
//! supports_receipts: false,
//! supports_attachments: true,
//! supports_rich_content: true,
//! supports_templates: false,
//! max_attachment_size: Some(10 * 1024 * 1024),
//! rate_limit: Some(100),
//! }
//! }
//! }
//! ```
//!
//! # Common Pitfalls
//!
//! 1. **Not Checking Capabilities**: Always check `capabilities()` before using advanced features
//! 2. **Ignoring Rate Limits**: Respect provider rate limits to avoid account suspension
//! 3. **Blocking on Delivery**: Use QueuePort for async delivery to avoid blocking agents
//! 4. **Missing Error Context**: Include external_id and provider error messages for debugging
//! 5. **No Health Checks**: Implement health_check() to detect provider outages early
//! 6. **Template Injection**: Sanitize user input in template variables to prevent injection
//!
//! # Related Modules
//!
//! - [`paladin_core::platform::container::notification`] - Domain types for notifications
//! - [`crate::output::queue_port`] - Async notification delivery queue
//! - [`crate::output::llm_port`] - LLM integration for generating notification content
//! - [`crate::infrastructure::adapters::notification`] - Concrete notification adapters (SMTP, Twilio, etc.)
use async_trait;
use ;
use ;
use HashMap;
use Uuid;
// Re-export domain types for convenience
pub use ;
/// Result type for notification port operations
pub type NotificationPortResult<T> = ;
/// Errors that can occur in notification port operations
///
/// This enum represents all possible error conditions when interacting with notification
/// delivery systems. Each variant indicates a specific failure mode and provides guidance
/// on whether the operation should be retried.
///
/// # Error Categories
///
/// - **Transient Errors**: Can be retried (RateLimitExceeded, ServiceUnavailable, ConnectionError)
/// - **Permanent Errors**: Should not be retried (AuthenticationError, TemplateError, ValidationError)
/// - **Contextual Errors**: Retry depends on context (DeliveryFailed, StorageError)
///
/// # Examples
///
/// ```
/// use paladin::application::ports::output::notification_port::NotificationPortError;
///
/// // Check if an error should be retried
/// fn should_retry(error: &NotificationPortError) -> bool {
/// matches!(
/// error,
/// NotificationPortError::RateLimitExceeded
/// | NotificationPortError::ServiceUnavailable(_)
/// | NotificationPortError::ConnectionError(_)
/// | NotificationPortError::Timeout
/// )
/// }
/// ```
/// Delivery result for notification operations
/// Bulk delivery result
/// Notification statistics
/// Channel-specific statistics
/// Query filters for notifications
/// Fields available for sorting
/// Sort order
// ============================================================================
// OUTPUT PORTS (INTERFACES)
// ============================================================================
/// Core notification delivery port
///
/// This port defines the essential delivery functionality that all notification
/// adapters must implement. It focuses purely on the delivery mechanism and provides
/// a channel-specific abstraction for sending notifications through various providers.
///
/// # Capabilities
///
/// - **Channel-Specific Delivery**: Each port handles one notification channel (Email, SMS, Push, etc.)
/// - **Single & Bulk Delivery**: Send individual notifications or batches for efficiency
/// - **Health Monitoring**: Check provider availability before sending
/// - **Capability Discovery**: Query supported features (attachments, templates, rate limits)
/// - **Async Execution**: All delivery operations are asynchronous for non-blocking performance
///
/// # Requirements
///
/// Implementations must:
/// - Be `Send + Sync` for safe concurrent use across async tasks
/// - Return accurate channel information via `channel()`
/// - Implement `can_handle()` to filter notifications by channel
/// - Provide comprehensive error context in `NotificationPortError`
/// - Track delivery status and external IDs for tracing
/// - Respect rate limits indicated in `capabilities()`
/// - Implement `health_check()` for circuit breaker patterns
///
/// # Examples
///
/// ## Basic Notification Delivery
///
/// ```ignore
/// use paladin::application::ports::output::notification_port::{
/// NotificationDeliveryPort, NotificationPortError
/// };
/// use paladin::core::platform::container::notification::{
/// Notification, NotificationChannel, NotificationContent,
/// NotificationRecipient, NotificationPriority
/// };
/// use std::sync::Arc;
///
/// async fn send_alert(
/// port: Arc<dyn NotificationDeliveryPort>,
/// ) -> Result<(), NotificationPortError> {
/// // Build notification
/// let notification = Notification::builder()
/// .recipient(NotificationRecipient::email("admin@example.com"))
/// .channel(NotificationChannel::Email)
/// .priority(NotificationPriority::High)
/// .content(NotificationContent::text(
/// "System Alert",
/// "High CPU usage detected on production server"
/// ))
/// .build()?;
///
/// // Check if port can handle this channel
/// if !port.can_handle(¬ification) {
/// return Err(NotificationPortError::ValidationError(
/// "Port cannot handle this notification channel".into()
/// ));
/// }
///
/// // Deliver notification
/// let result = port.deliver_notification(notification).await?;
/// println!("Delivered via {}: {:?}", result.channel, result.status);
/// Ok(())
/// }
/// ```
///
/// ## Health Check Before Delivery
///
/// ```ignore
/// use paladin::application::ports::output::notification_port::{
/// NotificationDeliveryPort, NotificationPortError
/// };
/// use std::sync::Arc;
/// use std::time::Duration;
/// use tokio::time::sleep;
///
/// async fn send_with_health_check(
/// port: Arc<dyn NotificationDeliveryPort>,
/// notification: paladin::core::platform::container::notification::Notification,
/// ) -> Result<(), NotificationPortError> {
/// // Check health before sending
/// if !port.health_check().await {
/// // Wait and retry health check
/// sleep(Duration::from_secs(5)).await;
/// if !port.health_check().await {
/// return Err(NotificationPortError::ServiceUnavailable(
/// "Notification service is down".into()
/// ));
/// }
/// }
///
/// port.deliver_notification(notification).await?;
/// Ok(())
/// }
/// ```
///
/// ## Query Capabilities
///
/// ```ignore
/// use paladin::application::ports::output::notification_port::NotificationDeliveryPort;
/// use std::sync::Arc;
///
/// fn check_capabilities(port: Arc<dyn NotificationDeliveryPort>) {
/// let caps = port.capabilities();
///
/// if caps.supports_bulk {
/// println!("Port supports bulk delivery");
/// }
///
/// if let Some(limit) = caps.rate_limit {
/// println!("Rate limit: {} messages/minute", limit);
/// }
///
/// if let Some(max_size) = caps.max_attachment_size {
/// println!("Max attachment size: {} bytes", max_size);
/// }
/// }
/// ```
///
/// # Implementation Notes
///
/// ## Error Handling
///
/// Map provider-specific errors to appropriate `NotificationPortError` variants:
/// - Network errors → `ConnectionError`
/// - API auth failures → `AuthenticationError`
/// - Rate limiting → `RateLimitExceeded`
/// - Service outages → `ServiceUnavailable`
/// - Invalid data → `ValidationError`
///
/// ## Performance Tips
///
/// 1. **Connection Pooling**: Reuse HTTP/SMTP connections across deliveries
/// 2. **Bulk Delivery**: Override `deliver_bulk()` with native provider bulk APIs when available
/// 3. **Async I/O**: Use tokio for non-blocking external calls
/// 4. **Timeout Configuration**: Set reasonable timeouts (5-30 seconds typical)
/// 5. **Circuit Breaker**: Use `health_check()` to detect provider outages early
///
/// ## Testing
///
/// See module-level documentation for mock implementation example.
/// Delivery capabilities supported by a port
/// Notification template port
///
/// This port handles template management and content rendering for notifications.
/// Templates allow you to define reusable notification formats with variable
/// substitution, supporting multiple channels and localization.
///
/// # Capabilities
///
/// - **Template CRUD**: Create, read, update, delete notification templates
/// - **Variable Rendering**: Render templates with dynamic variables
/// - **Channel Support**: Filter templates by notification channel
/// - **Syntax Validation**: Validate template syntax before saving
/// - **Localization**: Support for multi-language templates (implementation-specific)
///
/// # Requirements
///
/// Implementations must:
/// - Support variable substitution with safe escaping
/// - Validate template syntax to prevent injection attacks
/// - Handle missing variables gracefully (error or default values)
/// - Be thread-safe (`Send + Sync`)
///
/// # Examples
///
/// ## Create and Render Template
///
/// ```ignore
/// use paladin::application::ports::output::notification_port::{
/// NotificationTemplatePort, NotificationPortError
/// };
/// use paladin::core::platform::container::notification::{
/// NotificationTemplate, NotificationChannel
/// };
/// use std::collections::HashMap;
/// use std::sync::Arc;
///
/// async fn use_template(
/// port: Arc<dyn NotificationTemplatePort>,
/// ) -> Result<(), NotificationPortError> {
/// // Create template
/// let template = NotificationTemplate::new(
/// "welcome_email",
/// NotificationChannel::Email,
/// "Welcome {{user_name}}!",
/// "Hello {{user_name}}, welcome to our platform!"
/// );
///
/// let template_id = port.create_template(template).await?;
///
/// // Render with variables
/// let mut vars = HashMap::new();
/// vars.insert("user_name".to_string(), serde_json::json!("Alice"));
///
/// let content = port.render_template(&template_id, vars).await?;
/// println!("Subject: {}", content.subject);
/// println!("Body: {}", content.body);
/// Ok(())
/// }
/// ```
///
/// ## List and Validate Templates
///
/// ```ignore
/// use paladin::application::ports::output::notification_port::NotificationTemplatePort;
/// use paladin::core::platform::container::notification::NotificationChannel;
/// use std::sync::Arc;
///
/// async fn audit_templates(port: Arc<dyn NotificationTemplatePort>) {
/// // List all email templates
/// let templates = port
/// .list_templates(Some(NotificationChannel::Email))
/// .await
/// .unwrap();
///
/// for template in templates {
/// // Validate each template
/// match port.validate_template(&template).await {
/// Ok(_) => println!("✓ Template '{}' is valid", template.name),
/// Err(e) => println!("✗ Template '{}' invalid: {}", template.name, e),
/// }
/// }
/// }
/// ```
///
/// # Implementation Notes
///
/// ## Template Engines
///
/// Common template engines for Rust:
/// - **Handlebars**: `{{variable}}` syntax, helpers, partials
/// - **Tera**: Django/Jinja2-like syntax, filters, macros
/// - **Liquid**: Shopify's template language
/// - **Askama**: Compile-time type-safe templates
///
/// ## Security
///
/// - **Sanitize Variables**: Escape HTML in email templates to prevent XSS
/// - **Validate Syntax**: Reject templates with invalid syntax at creation time
/// - **Limit Complexity**: Prevent templates from executing arbitrary code
/// - **Audit Access**: Log template modifications for security auditing
///
/// ## Performance
///
/// - **Template Caching**: Cache compiled templates to avoid repeated parsing
/// - **Async Rendering**: Render templates asynchronously for large batches
/// - **Precompilation**: Compile templates at startup for production use
/// Basic notification port for simple use cases
///
/// This trait combines delivery functionality with a simplified API for straightforward
/// notification scenarios. It's a convenience wrapper around `NotificationDeliveryPort`
/// for applications that don't need template management or advanced features.
///
/// Use this trait when you:
/// - Only need basic send functionality
/// - Don't use templates or complex workflows
/// - Want a simpler API surface
///
/// # Examples
///
/// ```ignore
/// use paladin::application::ports::output::notification_port::{
/// BasicNotificationPort, NotificationPortError
/// };
/// use paladin::core::platform::container::notification::{
/// Notification, NotificationChannel, NotificationContent, NotificationRecipient
/// };
/// use std::sync::Arc;
///
/// async fn send_simple(
/// port: Arc<dyn BasicNotificationPort>,
/// ) -> Result<(), NotificationPortError> {
/// let notification = Notification::builder()
/// .recipient(NotificationRecipient::email("user@example.com"))
/// .channel(NotificationChannel::Email)
/// .content(NotificationContent::text("Hello", "This is a test"))
/// .build()?;
///
/// port.send_notification(notification).await?;
/// Ok(())
/// }
/// ```
/// Configuration for notification ports