defmodule WhoNeedHelp.Trust.AbuseSignal do
  use Ecto.Schema
  import Ecto.Changeset

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

  schema "abuse_signals" do
    field :kind, Ecto.Enum,
      values: [
        :velocity,
        :repeated_pair,
        :handover_without_location_evidence,
        :location_without_movement,
        :reciprocal_ring,
        :manual
      ]

    field :status, Ecto.Enum, values: [:open, :reviewed, :dismissed], default: :open
    field :metadata, :map, default: %{}
    field :reviewed_at, :utc_datetime
    field :review_note, :string
    belongs_to :subject, WhoNeedHelp.Accounts.User
    belongs_to :assignment, WhoNeedHelp.Help.Assignment
    belongs_to :reviewed_by, WhoNeedHelp.Accounts.User
    timestamps(type: :utc_datetime)
  end

  def changeset(signal, attrs) do
    signal
    |> cast(attrs, [:kind, :status, :metadata, :subject_id, :assignment_id])
    |> validate_required([:kind, :subject_id])
    |> unique_constraint([:kind, :subject_id, :assignment_id],
      name: :abuse_signals_one_kind_per_assignment
    )
    |> unique_constraint(:subject_id, name: :abuse_signals_one_open_velocity_per_subject)
  end

  def moderation_changeset(signal, attrs) do
    signal
    |> cast(attrs, [:status, :reviewed_at, :review_note, :reviewed_by_id])
    |> validate_required([:status, :reviewed_at, :reviewed_by_id])
    |> validate_length(:review_note, max: 1_000)
  end
end
