-- Migration: 003_create_audit_events
-- Creates the audit_events table for the Audit Log service.
-- Append-only by design — no UPDATE or DELETE operations are permitted.

CREATE TABLE IF NOT EXISTS audit_events (
  event_id    UUID        PRIMARY KEY DEFAULT gen_random_uuid(),
  agent_id    UUID        NOT NULL,
  action      VARCHAR(32) NOT NULL,
  outcome     VARCHAR(16) NOT NULL,
  ip_address  VARCHAR(64) NOT NULL,
  user_agent  TEXT        NOT NULL,
  metadata    JSONB       NOT NULL DEFAULT '{}',
  timestamp   TIMESTAMPTZ NOT NULL DEFAULT NOW(),

  CONSTRAINT audit_events_action_check
    CHECK (action IN (
      'agent.created','agent.updated','agent.decommissioned','agent.suspended',
      'agent.reactivated','token.issued','token.revoked','token.introspected',
      'credential.generated','credential.rotated','credential.revoked','auth.failed'
    )),
  CONSTRAINT audit_events_outcome_check
    CHECK (outcome IN ('success','failure'))
);

CREATE INDEX IF NOT EXISTS idx_audit_events_agent_id   ON audit_events (agent_id);
CREATE INDEX IF NOT EXISTS idx_audit_events_action     ON audit_events (action);
CREATE INDEX IF NOT EXISTS idx_audit_events_outcome    ON audit_events (outcome);
CREATE INDEX IF NOT EXISTS idx_audit_events_timestamp  ON audit_events (timestamp DESC);
