-- Audit log. Fabric's audit service flushes events here via a per-stage
-- CF Queue. Add this table if you want audit capture; remove it (and skip
-- this migration) if your project has no audit requirements.
CREATE TABLE IF NOT EXISTS audit (
  audit_id       TEXT    NOT NULL PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),
  occurred_at    TEXT    NOT NULL DEFAULT (datetime('now')),
  type           TEXT    NOT NULL,
  source         TEXT    NOT NULL DEFAULT 'auto',
  outcome        TEXT,
  function_id    TEXT,
  wire_type      TEXT,
  trace_id       TEXT,
  transaction_id TEXT,
  query_id       TEXT,
  actor_user_id  TEXT,
  actor_org_id   TEXT,
  tables         TEXT,  -- JSON array of table names touched
  changed_cols   TEXT,  -- JSON array of changed column names
  event          TEXT,  -- custom event label
  old            TEXT,  -- JSON: previous values
  data           TEXT   -- JSON: new values / event payload
);

CREATE INDEX IF NOT EXISTS idx_audit_occurred_at  ON audit (occurred_at);
CREATE INDEX IF NOT EXISTS idx_audit_actor        ON audit (actor_user_id) WHERE actor_user_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_audit_function     ON audit (function_id)   WHERE function_id  IS NOT NULL;
