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, Towerops.EctoTypes.IpAddress
    field :user_agent, :string
    field :request_path, :string
    field :data_accessed, :map

    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,
      :user_agent,
      :request_path,
      :data_accessed
    ])
    |> validate_required([:action])
    |> validate_inclusion(:action, [
      # Superuser actions
      "impersonate_start",
      "impersonate_end",
      "user_delete",
      "org_delete",
      "agent_debug_enable",
      "agent_debug_disable",
      # User data access
      "user_data_viewed",
      "user_data_exported",
      "user_profile_updated",
      # Organization actions
      "org_data_accessed",
      # Device actions
      "device_created",
      "device_updated",
      "device_deleted",
      # Monitoring actions
      "monitoring_data_queried",
      # Security events
      "failed_access_attempt",
      "privilege_escalation",
      "sudo_mode_granted"
    ])
  end
end
