defmodule Cannery.Ammo.Pack do
  @moduledoc """
  A group of a certain ammunition type.

  Can be placed in a container, and contains auxiliary information such as the
  amount paid for that ammunition, or what condition it is in
  """

  use Cannery, :schema
  alias Cannery.{Ammo.Type, Containers, Containers.Container}

  @derive {Jason.Encoder,
           only: [
             :container_id,
             :count,
             :id,
             :lot_number,
             :notes,
             :price_paid,
             :type_id
           ]}
  schema "packs" do
    field :count, :integer
    field :lot_number, :string
    field :notes, :string
    field :price_paid, :float
    field :purchased_on, :date

    belongs_to :type, Type
    field :container_id, :binary_id
    field :user_id, :binary_id

    timestamps(type: :utc_datetime_usec)
  end

  @type t :: %__MODULE__{
          count: integer,
          id: id(),
          lot_number: String.t() | nil,
          notes: String.t() | nil,
          price_paid: float() | nil,
          purchased_on: Date.t(),
          type: Type.t() | nil,
          type_id: Type.id(),
          container_id: Container.id(),
          user_id: User.id(),
          inserted_at: DateTime.t(),
          updated_at: DateTime.t()
        }
  @type new_pack :: %__MODULE__{}
  @type id :: UUID.t()
  @type changeset :: Changeset.t(t() | new_pack())

  @doc false
  @spec create_changeset(
          new_pack(),
          Type.t() | nil,
          Container.t() | nil,
          User.t(),
          attrs :: map()
        ) :: changeset()
  def create_changeset(
        pack,
        type,
        container,
        %User{id: user_id},
        attrs
      )
      when is_binary(user_id) do
    type_id =
      case type do
        %Type{id: type_id} when is_binary(type_id) ->
          type_id

        _invalid_type ->
          nil
      end

    container_id =
      case container do
        %Container{id: container_id, user_id: ^user_id} when is_binary(container_id) ->
          container_id

        _invalid_container ->
          nil
      end

    pack
    |> change(type_id: type_id)
    |> change(container_id: container_id)
    |> change(user_id: user_id)
    |> cast(attrs, [
      :count,
      :lot_number,
      :notes,
      :price_paid,
      :purchased_on
    ])
    |> validate_required(:type_id, message: dgettext("errors", "Please select a valid type"))
    |> validate_required(:container_id,
      message: dgettext("errors", "Please select a valid container")
    )
    |> validate_number(:count, greater_than: 0)
    |> validate_number(:price_paid, greater_than_or_equal_to: 0)
    |> validate_length(:lot_number, max: 255)
    |> validate_required([
      :container_id,
      :count,
      :purchased_on,
      :type_id,
      :user_id
    ])
  end

  @doc false
  @spec update_changeset(t() | new_pack(), attrs :: map(), User.t()) :: changeset()
  def update_changeset(pack, attrs, user) do
    pack
    |> cast(attrs, [
      :container_id,
      :count,
      :lot_number,
      :notes,
      :price_paid,
      :purchased_on
    ])
    |> validate_number(:count, greater_than_or_equal_to: 0)
    |> validate_number(:price_paid, greater_than_or_equal_to: 0)
    |> validate_container_id(user)
    |> validate_length(:lot_number, max: 255)
    |> validate_required([
      :container_id,
      :count,
      :purchased_on
    ])
  end

  defp validate_container_id(changeset, user) do
    container_id = changeset |> Changeset.get_field(:container_id)

    if container_id do
      Containers.get_container!(container_id, user)
    end

    changeset
  end

  @doc """
  This range changeset is used when "using up" packs, and allows for
  updating the count to 0
  """
  @spec range_changeset(t() | new_pack(), attrs :: map()) :: changeset()
  def range_changeset(pack, attrs) do
    pack
    |> cast(attrs, [:count])
    |> validate_required([:count])
  end
end
