defmodule Towerops.ApiTokens.ApiToken do
  @moduledoc """
  Schema for API tokens scoped to organizations.

  API tokens allow programmatic access to the Towerops API for managing
  sites, devices, and other resources within an organization.

  The actual token value is only shown once when created and is then
  hashed for secure storage.
  """
  use Ecto.Schema

  import Ecto.Changeset

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

  schema "api_tokens" do
    field :name, :string
    field :token_hash, :string
    field :last_used_at, :utc_datetime
    field :expires_at, :utc_datetime

    belongs_to :organization, Towerops.Organizations.Organization
    belongs_to :user, Towerops.Accounts.User

    timestamps(type: :utc_datetime)
  end

  @doc false
  def changeset(api_token, attrs) do
    api_token
    |> cast(attrs, [:organization_id, :user_id, :name, :token_hash, :expires_at, :last_used_at])
    |> validate_required([:organization_id, :name, :token_hash])
    |> validate_length(:name, min: 1, max: 255)
    |> unique_constraint(:token_hash)
    |> foreign_key_constraint(:organization_id)
    |> foreign_key_constraint(:user_id)
  end
end
