hl7v2-server 1.3.0

HTTP/REST API server for HL7v2 message processing
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
//! Request and response models for the HTTP API.
//!
//! These models follow JSON:API conventions where appropriate and align
//! with the OpenAPI specification in `api/openapi/hl7v2-api-v1.yaml`.

use serde::{Deserialize, Serialize};
use std::path::PathBuf;

use hl7v2::{ValidationReport, ValidationReportIssue};

/// Health check response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthResponse {
    /// Service status
    pub status: HealthStatus,
    /// Service version
    pub version: String,
    /// Uptime in seconds
    pub uptime_seconds: u64,
}

/// Readiness check response.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReadyResponse {
    /// Whether the service is ready to receive traffic.
    pub ready: bool,
    /// Overall readiness status.
    pub status: ReadinessStatus,
    /// Server package version.
    pub version: String,
    /// Individual readiness checks.
    pub checks: Vec<ReadinessCheck>,
}

impl ReadyResponse {
    /// Build a readiness response from individual checks.
    pub fn from_checks(checks: Vec<ReadinessCheck>) -> Self {
        let ready = checks
            .iter()
            .all(|check| check.status == ReadinessCheckStatus::Pass);

        Self {
            ready,
            status: if ready {
                ReadinessStatus::Ready
            } else {
                ReadinessStatus::NotReady
            },
            version: env!("CARGO_PKG_VERSION").to_string(),
            checks,
        }
    }
}

/// Overall readiness status.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ReadinessStatus {
    /// All required checks passed.
    Ready,
    /// At least one required check failed.
    NotReady,
}

/// Individual readiness check.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ReadinessCheck {
    /// Stable check name.
    pub name: String,
    /// Check status.
    pub status: ReadinessCheckStatus,
    /// Human-readable diagnostic message.
    pub message: String,
}

impl ReadinessCheck {
    /// Build a passing readiness check.
    pub fn pass(name: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            status: ReadinessCheckStatus::Pass,
            message: message.into(),
        }
    }

    /// Build a failing readiness check.
    pub fn fail(name: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            status: ReadinessCheckStatus::Fail,
            message: message.into(),
        }
    }
}

/// Individual readiness check status.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ReadinessCheckStatus {
    /// Check passed.
    Pass,
    /// Check failed.
    Fail,
}

/// Health status enum
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum HealthStatus {
    /// Service is healthy
    Healthy,
    /// Service is degraded but functional
    Degraded,
    /// Service is unhealthy
    Unhealthy,
}

/// Parse request body
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParseRequest {
    /// Raw HL7 message content (can be MLLP framed or plain)
    pub message: String,
    /// Whether the message is MLLP framed
    #[serde(default)]
    pub mllp_framed: bool,
    /// Options for parsing
    #[serde(default)]
    pub options: ParseOptions,
}

/// Parse options
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ParseOptions {
    /// Return JSON representation of message
    #[serde(default = "default_true")]
    pub include_json: bool,
    /// Validate structure (segment IDs, delimiters)
    #[serde(default = "default_true")]
    pub validate_structure: bool,
}

fn default_true() -> bool {
    true
}

/// Parse response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParseResponse {
    /// Parsed message in JSON format
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<serde_json::Value>,
    /// Message metadata
    pub metadata: MessageMetadata,
    /// Parsing warnings (if any)
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub warnings: Vec<String>,
}

/// Message metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageMetadata {
    /// Message type (e.g., "ADT^A01")
    pub message_type: String,
    /// HL7 version (e.g., "2.5")
    pub version: String,
    /// Sending application
    pub sending_application: String,
    /// Sending facility
    pub sending_facility: String,
    /// Message control ID
    pub message_control_id: String,
    /// Number of segments
    pub segment_count: usize,
    /// Character sets used
    pub charsets: Vec<String>,
}

/// Validate request body
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidateRequest {
    /// Raw HL7 message content
    pub message: String,
    /// Inline profile YAML content to validate against
    pub profile: String,
    /// Whether the message is MLLP framed
    #[serde(default)]
    pub mllp_framed: bool,
}

/// Validate response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidateResponse {
    /// Whether validation passed
    pub valid: bool,
    /// HL7 trigger event from `MSH.9`, such as `ADT^A01`.
    pub message_type: String,
    /// Profile identifier, usually the loaded profile message structure.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile: Option<String>,
    /// Number of parsed message segments.
    pub segment_count: usize,
    /// Number of reported validation issues.
    pub issue_count: usize,
    /// Stable validation issue records.
    pub issues: Vec<ValidationReportIssue>,
    /// Validation errors
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub errors: Vec<ValidationError>,
    /// Validation warnings
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub warnings: Vec<ValidationWarning>,
    /// Message metadata
    pub metadata: MessageMetadata,
}

/// Validate and redact request body.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidateRedactedRequest {
    /// Raw HL7 message content.
    pub message: String,
    /// Inline profile YAML content to validate against.
    pub profile: String,
    /// Inline safe-analysis redaction policy in TOML format.
    pub redaction_policy: String,
    /// Whether the message is MLLP framed.
    #[serde(default)]
    pub mllp_framed: bool,
    /// Whether to include the redacted HL7 payload in the response.
    #[serde(default)]
    pub include_redacted_hl7: bool,
}

/// Validate and redact response body.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidateRedactedResponse {
    /// Validation report generated from the redacted message.
    pub validation_report: ValidationReport,
    /// Receipt describing redaction actions applied before validation.
    pub redaction_receipt: RedactionReceipt,
    /// Quarantine output written when configured and validation failed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quarantine: Option<QuarantineOutputSummary>,
    /// Redacted HL7 payload, included only when requested.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub redacted_hl7: Option<String>,
}

/// Server evidence bundle creation request body.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BundleRequest {
    /// Raw HL7 message content.
    pub message: String,
    /// Inline profile YAML content to validate against.
    pub profile: String,
    /// Inline safe-analysis redaction policy in TOML format.
    pub redaction_policy: String,
    /// Caller-supplied bundle identifier relative to the configured bundle root.
    pub bundle_id: String,
    /// Whether the message is MLLP framed.
    #[serde(default)]
    pub mllp_framed: bool,
}

/// Evidence bundle summary response body.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EvidenceBundleSummary {
    /// Evidence bundle contract version.
    pub bundle_version: String,
    /// Bundle output directory relative to the configured server bundle root.
    pub output_dir: String,
    /// HL7 trigger event from `MSH.9`, such as `ADT^A01`.
    pub message_type: String,
    /// Whether validation passed after redaction.
    pub validation_valid: bool,
    /// Number of validation issues generated from the redacted message.
    pub validation_issue_count: usize,
    /// Whether configured PHI paths were removed or hashed.
    pub redaction_phi_removed: bool,
    /// Bundle-relative artifact names written by the server.
    pub artifacts: Vec<String>,
}

/// Server quarantine output configuration.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct QuarantineConfig {
    /// Whether failed redacted validation should write quarantine output.
    #[serde(default)]
    pub enabled: bool,
    /// Filesystem root used for generated quarantine output.
    #[serde(default)]
    pub path: Option<PathBuf>,
    /// Whether to write `message.redacted.hl7` when not writing a full bundle.
    #[serde(default = "default_true")]
    pub write_redacted: bool,
    /// Whether to write `validation-report.json` when not writing a full bundle.
    #[serde(default = "default_true")]
    pub write_report: bool,
    /// Whether to write a full replayable evidence bundle.
    #[serde(default = "default_true")]
    pub write_bundle: bool,
}

impl Default for QuarantineConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            path: None,
            write_redacted: true,
            write_report: true,
            write_bundle: true,
        }
    }
}

/// Sanitized quarantine configuration for diagnostics.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PublicQuarantineConfig {
    /// Whether quarantine output is enabled.
    pub enabled: bool,
    /// Whether a quarantine output path is configured without exposing the path.
    pub path_configured: bool,
    /// Whether redacted HL7 artifacts are configured for quarantine output.
    pub write_redacted: bool,
    /// Whether validation report artifacts are configured for quarantine output.
    pub write_report: bool,
    /// Whether replayable bundle output is configured for quarantine output.
    pub write_bundle: bool,
}

/// Summary of quarantine output written by the server.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QuarantineOutputSummary {
    /// Quarantine output contract version.
    pub quarantine_version: String,
    /// Output directory relative to the configured quarantine root.
    pub output_dir: String,
    /// Stable reason for quarantine output.
    pub reason: QuarantineReason,
    /// Number of validation issues that triggered the quarantine write.
    pub validation_issue_count: usize,
    /// Quarantine-relative artifact names written by the server.
    pub artifacts: Vec<String>,
}

/// Reason that caused quarantine output.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum QuarantineReason {
    /// Validation report was invalid after redaction.
    ValidationError,
}

/// Evidence bundle manifest written inside the bundle directory.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EvidenceBundleManifest {
    /// Evidence bundle contract version.
    pub bundle_version: String,
    /// Tool that generated this bundle.
    pub tool_name: String,
    /// Tool version that generated this bundle.
    pub tool_version: String,
    /// Bundle-relative artifact entries.
    pub artifacts: Vec<EvidenceBundleManifestArtifact>,
}

/// Evidence bundle manifest artifact entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EvidenceBundleManifestArtifact {
    /// Bundle-relative artifact path.
    pub path: String,
    /// Stable artifact role.
    pub role: String,
    /// SHA-256 digest of the artifact bytes.
    pub sha256: String,
}

/// Environment metadata written inside an evidence bundle.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EvidenceBundleEnvironment {
    /// Evidence bundle contract version.
    pub bundle_version: String,
    /// Tool that generated this bundle.
    pub tool_name: String,
    /// Tool version that generated this bundle.
    pub tool_version: String,
    /// Message type from the raw message.
    pub message_type: String,
    /// SHA-256 digest of the raw input message.
    pub input_sha256: String,
    /// SHA-256 digest of the profile YAML.
    pub profile_sha256: String,
    /// SHA-256 digest of the redaction policy TOML.
    pub redaction_policy_sha256: String,
    /// Whether validation passed after redaction.
    pub validation_valid: bool,
    /// Number of validation issues generated from the redacted message.
    pub validation_issue_count: usize,
    /// Replay command for validating the bundled artifacts.
    pub replay_command: String,
}

/// Field-path trace written inside an evidence bundle.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FieldPathTraceReport {
    /// HL7 trigger event from `MSH.9`, such as `ADT^A01`.
    pub message_type: String,
    /// Number of field entries included in the trace.
    pub field_count: usize,
    /// Field path trace records.
    pub fields: Vec<FieldPathTrace>,
}

/// Field path trace record.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FieldPathTrace {
    /// Segment-position-qualified path.
    pub path: String,
    /// Segment and HL7 field path, such as `PID.3`.
    pub canonical_path: String,
    /// One-based segment index.
    pub segment_index: usize,
    /// One-based HL7 field index.
    pub field_index: usize,
    /// Whether the field value is present after redaction.
    pub present: bool,
    /// Shape of the redacted field value.
    pub value_shape: FieldValueShape,
    /// Redaction action associated with this path, when configured.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub redaction_action: Option<RedactionAction>,
}

/// Redacted field value shape.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum FieldValueShape {
    /// Empty field after redaction or original content.
    Empty,
    /// Non-empty value not matching a known redaction marker.
    Present,
    /// SHA-256 redaction marker.
    HashedSha256,
}

/// Redaction receipt compatible with evidence redaction receipts.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct RedactionReceipt {
    /// Whether any configured PHI-bearing field was removed or hashed.
    pub phi_removed: bool,
    /// Hash algorithm used by hash redaction actions.
    pub hash_algorithm: String,
    /// Per-rule redaction receipts.
    pub actions: Vec<RedactionActionReceipt>,
}

/// Per-rule redaction action receipt.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct RedactionActionReceipt {
    /// HL7 path covered by this policy action.
    pub path: String,
    /// Policy action applied to this path.
    pub action: RedactionAction,
    /// Policy reason for the action.
    pub reason: String,
    /// Number of matching values affected by this action.
    pub matched_count: usize,
    /// Whether missing matches are acceptable.
    pub optional: bool,
    /// Action status.
    pub status: RedactionActionStatus,
}

/// Safe-analysis redaction action.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum RedactionAction {
    /// Replace a field with a deterministic SHA-256 hash marker.
    Hash,
    /// Clear the field value.
    Drop,
    /// Keep a non-sensitive field unchanged.
    Retain,
}

/// Redaction action status.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum RedactionActionStatus {
    /// Action was applied to at least one field.
    Applied,
    /// Retain action matched at least one field.
    Retained,
    /// Optional action did not match a field.
    NotFound,
}

/// ACK generation request body
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AckRequest {
    /// Raw HL7 message content
    pub message: String,
    /// ACK code to generate
    pub code: AckRequestCode,
    /// Optional error text for ERR segment generation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_message: Option<String>,
    /// Whether the input message is MLLP framed
    #[serde(default)]
    pub mllp_framed: bool,
    /// Whether to MLLP frame the ACK response
    #[serde(default)]
    pub mllp_frame: bool,
}

/// HTTP ACK codes.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum AckRequestCode {
    /// Application accept
    #[serde(rename = "AA")]
    Aa,
    /// Application error
    #[serde(rename = "AE")]
    Ae,
    /// Application reject
    #[serde(rename = "AR")]
    Ar,
    /// Commit accept
    #[serde(rename = "CA")]
    Ca,
    /// Commit error
    #[serde(rename = "CE")]
    Ce,
    /// Commit reject
    #[serde(rename = "CR")]
    Cr,
}

impl AckRequestCode {
    /// Return the HL7 code string.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Aa => "AA",
            Self::Ae => "AE",
            Self::Ar => "AR",
            Self::Ca => "CA",
            Self::Ce => "CE",
            Self::Cr => "CR",
        }
    }
}

/// ACK generation response body
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AckResponse {
    /// Generated ACK message, optionally MLLP framed
    pub ack_message: String,
    /// Generated ACK code
    pub ack_code: String,
    /// Metadata extracted from the generated ACK message
    pub metadata: MessageMetadata,
}

/// Configurable server ACK policy.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct AckPolicyConfig {
    /// ACK mode to use when choosing generated ACK/NAK codes.
    #[serde(default)]
    pub mode: AckPolicyMode,
    /// Condition that causes an accept ACK.
    #[serde(default)]
    pub accept_on: AckPolicyAcceptOn,
    /// Conditions that cause reject ACKs.
    #[serde(default = "default_ack_reject_on")]
    pub reject_on: Vec<AckPolicyRejectCondition>,
    /// Whether generated NAKs should include non-PHI error text in `ERR`.
    #[serde(default = "default_include_error_text")]
    pub include_error_text: bool,
}

impl Default for AckPolicyConfig {
    fn default() -> Self {
        Self {
            mode: AckPolicyMode::Original,
            accept_on: AckPolicyAcceptOn::Valid,
            reject_on: default_ack_reject_on(),
            include_error_text: true,
        }
    }
}

impl AckPolicyConfig {
    /// Return whether the policy rejects the supplied condition.
    pub fn rejects(&self, condition: AckPolicyRejectCondition) -> bool {
        self.reject_on.contains(&condition)
    }
}

fn default_ack_reject_on() -> Vec<AckPolicyRejectCondition> {
    vec![
        AckPolicyRejectCondition::ParseError,
        AckPolicyRejectCondition::ValidationError,
    ]
}

fn default_include_error_text() -> bool {
    true
}

/// ACK policy mode.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum AckPolicyMode {
    /// Use original mode application ACK codes: `AA` and `AR`.
    #[default]
    Original,
    /// Use enhanced mode commit ACK codes: `CA` and `CR`.
    Enhanced,
}

/// ACK policy accept condition.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum AckPolicyAcceptOn {
    /// Accept only after the message validates against the supplied profile.
    #[default]
    Valid,
}

/// ACK policy reject condition.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum AckPolicyRejectCondition {
    /// Reject when the inbound message cannot be parsed enough to validate.
    ParseError,
    /// Reject when validation against the supplied profile fails.
    ValidationError,
}

/// Policy-driven ACK request body.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AckPolicyRequest {
    /// Raw HL7 message content.
    pub message: String,
    /// Inline profile YAML content used for validation before deciding ACK/NAK.
    pub profile: String,
    /// Whether the input message is MLLP framed.
    #[serde(default)]
    pub mllp_framed: bool,
    /// Whether to MLLP frame the ACK response.
    #[serde(default)]
    pub mllp_frame: bool,
}

/// Policy-driven ACK response body.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AckPolicyResponse {
    /// Generated ACK or NAK message, optionally MLLP framed.
    pub ack_message: String,
    /// Generated ACK code.
    pub ack_code: String,
    /// Decision details used to choose the ACK code.
    pub decision: AckPolicyDecision,
    /// Validation report used for the decision, when the message parsed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub validation_report: Option<hl7v2::ValidationReport>,
    /// Metadata extracted from the generated ACK message.
    pub metadata: MessageMetadata,
}

/// ACK policy decision details.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct AckPolicyDecision {
    /// Configured ACK mode.
    pub mode: AckPolicyMode,
    /// Decision outcome.
    pub outcome: AckPolicyOutcome,
    /// Reason for the decision.
    pub reason: AckPolicyReason,
    /// Generated ACK code.
    pub ack_code: String,
    /// Whether non-PHI error text was included in the ACK.
    pub include_error_text: bool,
    /// Error text included in the ACK, when configured.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_text: Option<String>,
}

/// ACK policy decision outcome.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum AckPolicyOutcome {
    /// Message was accepted.
    Accepted,
    /// Message was rejected.
    Rejected,
}

/// ACK policy decision reason.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum AckPolicyReason {
    /// Message parsed and validated successfully.
    Valid,
    /// Message could not be parsed.
    ParseError,
    /// Message parsed but failed profile validation.
    ValidationError,
}

/// Normalize request body
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NormalizeRequest {
    /// Raw HL7 message content
    pub message: String,
    /// Whether the input message is MLLP framed
    #[serde(default)]
    pub mllp_framed: bool,
    /// Normalization options
    #[serde(default)]
    pub options: NormalizeOptions,
}

/// Normalize options
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NormalizeOptions {
    /// Rewrite delimiters to canonical `|^~\&`
    #[serde(default = "default_true")]
    pub canonical_delimiters: bool,
    /// MLLP frame the normalized response
    #[serde(default)]
    pub mllp_frame: bool,
}

impl Default for NormalizeOptions {
    fn default() -> Self {
        Self {
            canonical_delimiters: true,
            mllp_frame: false,
        }
    }
}

/// Normalize response body
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NormalizeResponse {
    /// Normalized HL7 message, optionally MLLP framed
    pub normalized_message: String,
    /// Metadata extracted from the normalized message
    pub metadata: MessageMetadata,
}

/// Validation error
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationError {
    /// Error code (e.g., "V_RequiredField")
    pub code: String,
    /// Human-readable error message
    pub message: String,
    /// Location in message (e.g., `PID.5[1].1`)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub location: Option<String>,
    /// Severity level
    pub severity: ErrorSeverity,
}

/// Validation warning
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationWarning {
    /// Warning code
    pub code: String,
    /// Human-readable warning message
    pub message: String,
    /// Location in message
    #[serde(skip_serializing_if = "Option::is_none")]
    pub location: Option<String>,
}

/// Error severity
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ErrorSeverity {
    /// Fatal error, message cannot be processed
    Error,
    /// Warning, message can be processed but may have issues
    Warning,
    /// Informational, no action required
    Info,
}

/// Standard error response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorResponse {
    /// Error code
    pub code: String,
    /// Human-readable error message
    pub message: String,
    /// Additional error details
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<serde_json::Value>,
}

impl ErrorResponse {
    /// Create a new error response
    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            message: message.into(),
            details: None,
        }
    }

    /// Add details to the error response
    pub fn with_details(mut self, details: serde_json::Value) -> Self {
        self.details = Some(details);
        self
    }
}