defmodule Towerops.Admin.AuditLog do
  @moduledoc """
  Schema for audit logs tracking sensitive operations performed by superusers.
  """
  use Ecto.Schema

  import Ecto.Changeset

  alias Towerops.Accounts.User

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

  schema "audit_logs" do
    field :action, :string
    field :metadata, :map
    field :ip_address, :string

    belongs_to :superuser, User
    belongs_to :target_user, User

    timestamps(type: :utc_datetime, updated_at: false)
  end

  @doc false
  def changeset(audit_log, attrs) do
    audit_log
    |> cast(attrs, [:action, :superuser_id, :target_user_id, :metadata, :ip_address])
    |> validate_required([:action, :superuser_id])
    |> validate_inclusion(:action, [
      "impersonate_start",
      "impersonate_end",
      "user_delete",
      "org_delete"
    ])
  end
end
