# `HL7v2.Message`
[🔗](https://github.com/Balneario-de-Cofrentes/hl7v2/blob/v3.10.1/lib/hl7v2/message.ex#L1)

Programmatic HL7v2 message construction.

Low-level message constructor for building HL7v2 messages from typed segment
structs. The MSH segment is auto-populated with sensible defaults (field
separator, encoding characters, processing ID, version, timestamp, control ID)
and can be overridden via opts.

**Note:** This is an append-only builder — it does not enforce segment ordering
or required-segment presence. Use `HL7v2.validate/1` after building to check
structural conformance.

## Examples

    msg =
      HL7v2.Message.new("ADT", "A01",
        sending_application: "PHAOS",
        sending_facility: "HOSP"
      )
      |> HL7v2.Message.add_segment(%HL7v2.Segment.PID{
        patient_identifier_list: [%HL7v2.Type.CX{id: "12345"}],
        patient_name: [%HL7v2.Type.XPN{family_name: %HL7v2.Type.FN{surname: "Smith"}, given_name: "John"}]
      })

    wire = HL7v2.Message.encode(msg)

# `t`

```elixir
@type t() :: %HL7v2.Message{msh: HL7v2.Segment.MSH.t(), segments: [struct()]}
```

# `add_segment`

```elixir
@spec add_segment(
  t(),
  struct()
) :: t()
```

Adds a segment to the message.

Segments are appended in order. MSH is managed separately and cannot be added
via this function.

# `encode`

```elixir
@spec encode(t()) :: binary()
```

Encodes the message to HL7v2 wire format binary.

Converts to a `RawMessage` and delegates to `HL7v2.Encoder`.

# `new`

```elixir
@spec new(binary(), binary(), keyword()) :: t()
```

Creates a new message with MSH auto-populated.

## Options

  * `:sending_application` -- string or `%HD{}` (default `nil`)
  * `:sending_facility` -- string or `%HD{}` (default `nil`)
  * `:receiving_application` -- string or `%HD{}` (default `nil`)
  * `:receiving_facility` -- string or `%HD{}` (default `nil`)
  * `:date_time` -- `%TS{}` or `%DTM{}` (default: current UTC time)
  * `:message_control_id` -- string (default: auto-generated)
  * `:processing_id` -- string (default: `"P"`)
  * `:version_id` -- string (default: `"2.5.1"`)

# `segment`

```elixir
@spec segment(t(), module()) :: struct() | nil
```

Returns the first segment of a given type, or `nil`.

## Examples

    HL7v2.Message.segment(msg, HL7v2.Segment.PID)
    #=> %HL7v2.Segment.PID{...}

# `segments`

```elixir
@spec segments(t(), module()) :: [struct()]
```

Returns all segments of a given type.

## Examples

    HL7v2.Message.segments(msg, HL7v2.Segment.OBX)
    #=> [%HL7v2.Segment.OBX{...}, %HL7v2.Segment.OBX{...}]

# `to_raw`

```elixir
@spec to_raw(t()) :: HL7v2.RawMessage.t()
```

Converts to a `RawMessage` for encoding.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
