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

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

  @sources ~w(auto_slug_change auto_product_deleted analytics_auto_resolved admin)

  schema "redirects" do
    field :from_path, :string
    field :to_path, :string
    field :status_code, :integer, default: 301
    field :source, :string
    field :confidence, :float
    field :hit_count, :integer, default: 0

    timestamps()
  end

  def changeset(redirect, attrs) do
    redirect
    |> cast(attrs, [:from_path, :to_path, :status_code, :source, :confidence])
    |> validate_required([:from_path, :to_path, :source])
    |> validate_inclusion(:source, @sources)
    |> validate_inclusion(:status_code, [301, 302])
    |> validate_format(:from_path, ~r"^/", message: "must start with /")
    |> validate_format(:to_path, ~r"^/", message: "must start with /")
    |> unique_constraint(:from_path)
  end
end
