defmodule Berrypod.Redirects.BrokenUrl do
  use Ecto.Schema
  import Ecto.Changeset

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

  @statuses ~w(pending resolved ignored)

  schema "broken_urls" do
    field :path, :string
    field :prior_analytics_hits, :integer, default: 0
    field :recent_404_count, :integer, default: 1
    field :first_seen_at, :utc_datetime
    field :last_seen_at, :utc_datetime
    field :status, :string, default: "pending"

    belongs_to :resolved_redirect, Berrypod.Redirects.Redirect

    timestamps()
  end

  def changeset(broken_url, attrs) do
    broken_url
    |> cast(attrs, [
      :path,
      :prior_analytics_hits,
      :recent_404_count,
      :first_seen_at,
      :last_seen_at,
      :status,
      :resolved_redirect_id
    ])
    |> validate_required([:path, :first_seen_at, :last_seen_at])
    |> validate_inclusion(:status, @statuses)
    |> unique_constraint(:path)
  end
end
