defmodule Berrypod.Site.NavItem do
  use Ecto.Schema
  import Ecto.Changeset

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

  @locations ~w(header footer)

  schema "nav_items" do
    field :location, :string
    field :label, :string
    field :url, :string
    field :position, :integer, default: 0

    belongs_to :page, Berrypod.Pages.Page

    timestamps(type: :utc_datetime)
  end

  def locations, do: @locations

  @doc false
  def changeset(nav_item, attrs) do
    nav_item
    |> cast(attrs, [:location, :label, :url, :page_id, :position])
    |> validate_required([:location, :label])
    |> validate_inclusion(:location, @locations)
    |> validate_length(:label, min: 1, max: 50)
    |> foreign_key_constraint(:page_id)
    |> default_url()
  end

  # Default to empty string if URL not provided (allows pending page selection)
  defp default_url(changeset) do
    if get_field(changeset, :url) == nil do
      put_change(changeset, :url, "")
    else
      changeset
    end
  end
end
