CREATE TABLE IF NOT EXISTS audit_log (
  id TEXT PRIMARY KEY,
  event_id TEXT,
  source_app TEXT NOT NULL DEFAULT 'fw',
  action TEXT NOT NULL,
  severity TEXT NOT NULL DEFAULT 'info',
  actor_user_id TEXT,
  actor_email TEXT,
  actor_name TEXT,
  target_type TEXT,
  target_id TEXT,
  summary TEXT NOT NULL,
  details_json TEXT,
  ip TEXT,
  created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_audit_log_event_id ON audit_log(event_id) WHERE event_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_audit_log_created_at ON audit_log(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_audit_log_action ON audit_log(action);
