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

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

  schema "reviews" do
    field :rating, :integer
    field :comment, :string
    field :revealed_at, :utc_datetime
    belongs_to :assignment, WhoNeedHelp.Help.Assignment
    belongs_to :reviewer, WhoNeedHelp.Accounts.User
    belongs_to :reviewee, WhoNeedHelp.Accounts.User
    timestamps(type: :utc_datetime)
  end

  def changeset(review, attrs) do
    review
    |> cast(attrs, [:rating, :comment, :assignment_id, :reviewer_id, :reviewee_id])
    |> validate_required([:rating, :assignment_id, :reviewer_id, :reviewee_id])
    |> validate_number(:rating, greater_than_or_equal_to: 1, less_than_or_equal_to: 5)
    |> validate_length(:comment, max: 800)
    |> unique_constraint([:assignment_id, :reviewer_id])
    |> check_constraint(:reviewer_id, name: :review_cannot_target_self)
  end
end
