lib/qr_nbu/versions/v002.ex

defmodule QRNBU.Versions.V002 do
  @moduledoc """
  NBU QR Code Version 002 structure with validation and encoding.

  V002 uses Base64URL encoding with 13 fields as per NBU specification.

  ## Fields

  ### Required Fields
  - `:recipient` - Name of the recipient (validated by RecipientValidator)
  - `:iban` - Bank account IBAN (validated by IBANValidator)
  - `:recipient_code` - Recipient's identification code (validated by RecipientCodeValidator)
  - `:purpose` - Payment purpose description (validated by PurposeValidator)

  ### Optional Fields
  - `:amount` - Payment amount as Decimal (validated by AmountValidator)
  - `:reference` - Payment reference number (validated by ReferenceValidator)
  - `:function` - Payment function code: `:uct`, `:ict`, or `:xct` (default: `:uct`)
  - `:encoding` - Character encoding: `:utf8` or `:cp1251` (default: `:utf8`)

  ## Examples

      iex> QRNBU.Versions.V002.new(%{
      ...>   recipient: "ТОВ Компанія",
      ...>   iban: "UA213223130000026007233566001",
      ...>   recipient_code: "12345678",
      ...>   purpose: "Оплата товарів"
      ...> })
      {:ok, %QRNBU.Versions.V002{...}}

      iex> QRNBU.Versions.V002.new(%{
      ...>   recipient: "ТОВ Компанія",
      ...>   iban: "UA213223130000026007233566001",
      ...>   amount: Decimal.new("100.50"),
      ...>   recipient_code: "12345678",
      ...>   reference: "INV-12345",
      ...>   purpose: "Оплата товарів",
      ...>   function: :uct,
      ...>   encoding: :utf8
      ...> })
      {:ok, %QRNBU.Versions.V002{...}}

  """

  alias QRNBU.Validators.{
    Recipient,
    IBAN,
    RecipientCode,
    Purpose,
    Amount,
    Reference,
    Display,
    FunctionCode
  }

  alias QRNBU.Encoders.Formatter

  @type t :: %__MODULE__{
          recipient: String.t(),
          iban: String.t(),
          recipient_code: String.t(),
          purpose: String.t(),
          amount: Decimal.t() | nil,
          reference: String.t() | nil,
          display: String.t() | nil,
          function: :uct | :ict | :xct,
          encoding: :utf8 | :cp1251
        }

  @enforce_keys [:recipient, :iban, :recipient_code, :purpose]
  defstruct [
    :recipient,
    :iban,
    :recipient_code,
    :purpose,
    :amount,
    :reference,
    :display,
    function: :uct,
    encoding: :utf8
  ]

  @doc """
  Creates a new V002 QR code structure with validation.

  ## Parameters

  - `attrs` - Map with required and optional fields

  ## Returns

  - `{:ok, %QRNBU.Versions.V002{}}` - Valid V002 structure
  - `{:error, String.t()}` - Validation error message

  ## Examples

      iex> QRNBU.Versions.V002.new(%{
      ...>   recipient: "ТОВ Компанія",
      ...>   iban: "UA213223130000026007233566001",
      ...>   recipient_code: "12345678",
      ...>   purpose: "Оплата товарів"
      ...> })
      {:ok, %QRNBU.Versions.V002{}}

      iex> QRNBU.Versions.V002.new(%{
      ...>   recipient: "",
      ...>   iban: "invalid",
      ...>   recipient_code: "123",
      ...>   purpose: ""
      ...> })
      {:error, "Recipient name is required"}

  """
  @spec new(map()) :: {:ok, t()} | {:error, String.t()}
  def new(attrs) when is_map(attrs) do
    with :ok <- validate_required_fields(attrs),
         {:ok, validated_attrs} <- validate_fields(attrs) do
      struct = struct(__MODULE__, validated_attrs)
      {:ok, struct}
    end
  end

  @doc """
  Encodes a V002 structure into the NBU QR code data string.

  Returns the Base64URL encoded format with https://qr.bank.gov.ua/ prefix.

  ## Parameters

  - `v002` - V002 structure to encode

  ## Returns

  - `{:ok, String.t()}` - Encoded QR data string
  - `{:error, String.t()}` - Encoding error

  ## Examples

      iex> {:ok, v002} = QRNBU.Versions.V002.new(%{...})
      iex> QRNBU.Versions.V002.encode(v002)
      {:ok, "https://qr.bank.gov.ua/MQpVQ1QKVUFICgo..."}

  """
  @spec encode(t()) :: {:ok, String.t()} | {:error, String.t()}
  def encode(%__MODULE__{} = v002) do
    data = %{
      recipient: v002.recipient,
      iban: v002.iban,
      recipient_code: v002.recipient_code,
      purpose: v002.purpose,
      amount: v002.amount,
      reference: v002.reference,
      display: v002.display,
      function: v002.function
    }

    opts = [encoding: v002.encoding]
    Formatter.format_v002(data, opts)
  end

  # Private Functions

  defp validate_required_fields(attrs) do
    required = [:recipient, :iban, :recipient_code, :purpose]

    missing =
      Enum.filter(required, fn key ->
        not Map.has_key?(attrs, key) or is_nil(Map.get(attrs, key))
      end)

    case missing do
      [] -> :ok
      [field | _] -> {:error, "Missing required field: #{field}"}
    end
  end

  defp validate_fields(attrs) do
    encoding = Map.get(attrs, :encoding, :utf8)

    with {:ok, recipient} <- Recipient.validate(attrs.recipient, encoding: encoding),
         {:ok, iban} <- IBAN.validate(attrs.iban),
         {:ok, recipient_code} <- RecipientCode.validate(attrs.recipient_code),
         {:ok, purpose} <- Purpose.validate(attrs.purpose, encoding: encoding),
         {:ok, amount} <- validate_optional_amount(Map.get(attrs, :amount)),
         {:ok, reference} <- validate_optional_reference(Map.get(attrs, :reference)),
         {:ok, display} <- validate_optional_display(Map.get(attrs, :display), encoding),
         {:ok, function} <- validate_function(Map.get(attrs, :function, :uct)),
         {:ok, encoding} <- validate_encoding(encoding) do
      validated = %{
        recipient: recipient,
        iban: iban,
        recipient_code: recipient_code,
        purpose: purpose,
        amount: amount,
        reference: reference,
        display: display,
        function: function,
        encoding: encoding
      }

      {:ok, validated}
    end
  end

  defp validate_optional_amount(nil), do: {:ok, nil}

  defp validate_optional_amount(amount) do
    Amount.validate(amount)
  end

  defp validate_optional_reference(nil), do: {:ok, nil}

  defp validate_optional_reference(reference) do
    Reference.validate(reference)
  end

  defp validate_optional_display(nil, _encoding), do: {:ok, nil}

  defp validate_optional_display(display, encoding) do
    Display.validate(display, encoding: encoding)
  end

  defp validate_function(function) do
    FunctionCode.validate(function)
  end

  defp validate_encoding(encoding) when encoding in [:utf8, :cp1251] do
    {:ok, encoding}
  end

  defp validate_encoding(encoding) do
    {:error, "Invalid encoding: #{inspect(encoding)}. Must be :utf8 or :cp1251"}
  end
end