-- Migration 005: Policy (risk classes, approval rules, autonomy settings)

CREATE TABLE risk_classes (
    name              TEXT PRIMARY KEY,
    description       TEXT,
    approval_required TEXT NOT NULL DEFAULT 'none',
    autonomy_allowed  BOOLEAN NOT NULL DEFAULT false
);

CREATE TABLE approval_rules (
    id                UUID PRIMARY KEY,
    entity_type       TEXT REFERENCES entity_types(name),
    action            TEXT NOT NULL,
    risk_class        TEXT NOT NULL REFERENCES risk_classes(name),
    autonomy_level    TEXT NOT NULL DEFAULT 'escalate' CHECK
                        (autonomy_level IN ('auto','escalate','never')),
    scope_entity      UUID REFERENCES entities(id),
    version           INTEGER NOT NULL DEFAULT 1,
    updated_at        TIMESTAMPTZ NOT NULL DEFAULT now(),
    UNIQUE (entity_type, action, scope_entity)
);

CREATE TABLE autonomy_settings (
    key               TEXT PRIMARY KEY,
    value             TEXT NOT NULL,
    version           INTEGER NOT NULL DEFAULT 1,
    updated_at        TIMESTAMPTZ NOT NULL DEFAULT now()
);
