defmodule Berrypod.Newsletter.Subscriber do
  use Ecto.Schema
  import Ecto.Changeset

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

  schema "newsletter_subscribers" do
    field :email, :string
    field :status, :string, default: "pending"
    field :confirmation_token, :string
    field :confirmed_at, :utc_datetime
    field :unsubscribed_at, :utc_datetime
    field :consent_text, :string
    field :source, :string, default: "website"
    field :ip_hash, :string

    timestamps(type: :utc_datetime)
  end

  def changeset(subscriber, attrs) do
    subscriber
    |> cast(attrs, [
      :email,
      :status,
      :confirmation_token,
      :confirmed_at,
      :unsubscribed_at,
      :consent_text,
      :source,
      :ip_hash
    ])
    |> validate_required([:email])
    |> validate_format(:email, ~r/^[^\s@]+@[^\s@]+\.[^\s@]+$/)
    |> validate_inclusion(:status, ~w(pending confirmed unsubscribed))
    |> unique_constraint(:email)
    |> update_change(:email, &String.downcase(String.trim(&1)))
  end
end
