CREATE TABLE IF NOT EXISTS audit_events (
    id              BIGSERIAL PRIMARY KEY,
    type            TEXT NOT NULL DEFAULT 'tool_call_evaluated',
    timestamp       TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    trace_id        TEXT NOT NULL DEFAULT '',
    agent_id        TEXT NOT NULL DEFAULT '',
    tool            TEXT NOT NULL DEFAULT '',
    action          TEXT NOT NULL DEFAULT '',
    decision        TEXT NOT NULL,
    reason          TEXT NOT NULL DEFAULT '',
    policy          TEXT NOT NULL DEFAULT '',
    amount          BIGINT,
    risk_score      DOUBLE PRECISION,
    http_path       TEXT NOT NULL DEFAULT '',
    http_method     TEXT NOT NULL DEFAULT '',
    principal_sub   TEXT NOT NULL DEFAULT '',
    principal_roles JSONB NOT NULL DEFAULT '[]'::jsonb
);

CREATE INDEX IF NOT EXISTS idx_audit_events_ts ON audit_events (timestamp DESC);
CREATE INDEX IF NOT EXISTS idx_audit_events_trace ON audit_events (trace_id);
CREATE INDEX IF NOT EXISTS idx_audit_events_agent ON audit_events (agent_id);

CREATE TABLE IF NOT EXISTS approval_records (
    trace_id         TEXT PRIMARY KEY,
    status           TEXT NOT NULL,
    agent_id         TEXT NOT NULL,
    tool             TEXT NOT NULL,
    action           TEXT NOT NULL,
    amount           BIGINT,
    risk_score       DOUBLE PRECISION,
    extra            JSONB,
    escalate_reason  TEXT NOT NULL DEFAULT '',
    policy           TEXT NOT NULL DEFAULT '',
    created_at       TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    decided_at       TIMESTAMPTZ,
    decided_by       TEXT NOT NULL DEFAULT ''
);

CREATE INDEX IF NOT EXISTS idx_approval_status_created
    ON approval_records (status, created_at DESC);

CREATE TABLE IF NOT EXISTS agents (
    agent_id      TEXT PRIMARY KEY,
    display_name  TEXT NOT NULL DEFAULT '',
    roles         JSONB NOT NULL DEFAULT '[]'::jsonb,
    tenant        TEXT NOT NULL DEFAULT 'default',
    status        TEXT NOT NULL DEFAULT 'active',
    metadata      JSONB NOT NULL DEFAULT '{}'::jsonb,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at    TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_agents_tenant ON agents (tenant);
CREATE INDEX IF NOT EXISTS idx_agents_status ON agents (status);
