defmodule Towerops.Accounts.PolicyVersion do
  @moduledoc """
  Policy version schema for tracking versions of privacy policy and terms of service.

  Stores the full text of each policy version with effective dates to maintain
  a complete audit trail of policy changes for GDPR compliance.
  """
  use Ecto.Schema

  import Ecto.Changeset

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id
  schema "policy_versions" do
    field :policy_type, :string
    field :version, :string
    field :content, :string
    field :effective_date, :utc_datetime

    timestamps(type: :utc_datetime)
  end

  @policy_types ~w(privacy_policy terms_of_service)

  @doc """
  Returns the list of valid policy types.
  """
  def policy_types, do: @policy_types

  @doc """
  Changeset for creating a new policy version.
  """
  def changeset(policy_version \\ %__MODULE__{}, attrs) do
    policy_version
    |> cast(attrs, [:policy_type, :version, :content, :effective_date])
    |> validate_required([:policy_type, :version, :content, :effective_date])
    |> validate_inclusion(:policy_type, @policy_types)
    |> validate_length(:version, min: 1, max: 20)
    |> validate_length(:content, min: 10)
    |> unique_constraint([:policy_type, :version])
  end
end
