BEGIN;

CREATE TABLE IF NOT EXISTS authz_records (
  seq BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  action TEXT NOT NULL,
  tenant_id TEXT NOT NULL,
  actor TEXT NOT NULL,
  allowed BOOLEAN NOT NULL,
  source TEXT NOT NULL,
  reason TEXT NOT NULL,
  at TIMESTAMPTZ NOT NULL,
  decision_id TEXT,
  request_digest TEXT,
  effect TEXT,
  stance TEXT
);
CREATE INDEX IF NOT EXISTS authz_records_tenant_seq_idx
  ON authz_records (tenant_id, seq);

CREATE TABLE IF NOT EXISTS audit_outbox (
  event_id TEXT PRIMARY KEY,
  tenant_id TEXT NOT NULL,
  envelope JSONB NOT NULL,
  created_at TIMESTAMPTZ NOT NULL,
  attempts INTEGER NOT NULL DEFAULT 0,
  last_error TEXT,
  delivered_at TIMESTAMPTZ,
  dead_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS audit_outbox_pending_idx
  ON audit_outbox (created_at) WHERE delivered_at IS NULL AND dead_at IS NULL;

COMMIT;
