defmodule WhoNeedHelp.Help.Assignment do
  use Ecto.Schema
  import Ecto.Changeset

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id

  schema "help_assignments" do
    field :status, Ecto.Enum,
      values: [:accepted, :in_progress, :completed, :cancelled],
      default: :accepted

    field :handover_code_hash, :binary
    field :handover_verified_at, :utc_datetime
    field :requester_confirmed_at, :utc_datetime
    field :helper_confirmed_at, :utc_datetime
    field :proximity_observed_at, :utc_datetime
    field :helper_movement_observed_at, :utc_datetime
    field :accepted_at, :utc_datetime
    field :started_at, :utc_datetime
    field :completed_at, :utc_datetime
    belongs_to :request, WhoNeedHelp.Help.HelpRequest
    belongs_to :helper, WhoNeedHelp.Accounts.User
    has_many :messages, WhoNeedHelp.Messaging.Message
    has_many :reviews, WhoNeedHelp.Trust.Review

    timestamps(type: :utc_datetime)
  end

  def changeset(assignment, attrs) do
    assignment
    |> cast(attrs, [
      :request_id,
      :helper_id,
      :status,
      :handover_code_hash,
      :handover_verified_at,
      :requester_confirmed_at,
      :helper_confirmed_at,
      :proximity_observed_at,
      :helper_movement_observed_at,
      :accepted_at,
      :started_at,
      :completed_at
    ])
    |> validate_required([:request_id, :helper_id, :status, :accepted_at, :handover_code_hash])
    |> unique_constraint(:request_id)
  end
end
