defmodule WhoNeedHelp.Catalog.CategoryProposal do
  use Ecto.Schema
  import Ecto.Changeset

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

  schema "category_proposals" do
    field :proposed_name, :string
    field :reason, :string
    field :mode, Ecto.Enum, values: [:help, :activity], default: :help
    field :status, Ecto.Enum, values: [:open, :approved, :rejected, :merged], default: :open
    belongs_to :proposer, WhoNeedHelp.Accounts.User
    belongs_to :parent, WhoNeedHelp.Catalog.Category
    belongs_to :merged_into, WhoNeedHelp.Catalog.Category
    belongs_to :reviewed_by, WhoNeedHelp.Accounts.User
    field :reviewed_at, :utc_datetime
    field :moderation_note, :string
    field :vote_count, :integer, virtual: true, default: 0
    has_many :votes, WhoNeedHelp.Catalog.CategoryVote, foreign_key: :proposal_id

    timestamps(type: :utc_datetime)
  end

  def changeset(proposal, attrs) do
    proposal
    |> cast(attrs, [:proposed_name, :reason, :mode, :parent_id])
    |> validate_required([:proposed_name, :reason, :mode])
    |> validate_length(:proposed_name, min: 2, max: 80)
    |> validate_length(:reason, min: 5, max: 500)
  end

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