defmodule WhoNeedHelp.Tracking.TrackingSession do
  use Ecto.Schema
  import Ecto.Changeset

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

  schema "tracking_sessions" do
    field :active, :boolean, default: true

    field :visibility, Ecto.Enum,
      values: [:active_match, :public],
      default: :active_match

    field :started_at, :utc_datetime
    field :ended_at, :utc_datetime
    field :distance_meters, :float, default: 0.0
    field :sample_count, :integer, default: 0
    field :movement_observed_at, :utc_datetime
    belongs_to :assignment, WhoNeedHelp.Help.Assignment
    belongs_to :user, WhoNeedHelp.Accounts.User
    has_one :position, WhoNeedHelp.Tracking.Position
    timestamps(type: :utc_datetime)
  end

  def changeset(session, attrs) do
    session
    |> cast(attrs, [
      :assignment_id,
      :user_id,
      :visibility,
      :active,
      :started_at,
      :ended_at,
      :distance_meters,
      :sample_count,
      :movement_observed_at
    ])
    |> validate_required([:assignment_id, :user_id, :visibility, :started_at])
    |> validate_number(:distance_meters, greater_than_or_equal_to: 0)
    |> validate_number(:sample_count, greater_than_or_equal_to: 0)
    |> unique_constraint([:assignment_id, :user_id],
      name: :tracking_sessions_one_active_per_user
    )
  end
end
