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

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

  schema "blocks" do
    belongs_to :blocker, WhoNeedHelp.Accounts.User
    belongs_to :blocked, WhoNeedHelp.Accounts.User
    timestamps(type: :utc_datetime, updated_at: false)
  end

  def changeset(block, attrs) do
    block
    |> cast(attrs, [:blocker_id, :blocked_id])
    |> validate_required([:blocker_id, :blocked_id])
    |> unique_constraint([:blocker_id, :blocked_id])
    |> check_constraint(:blocked_id, name: :block_cannot_target_self)
  end
end
