-- Migration 008: Decision Events / Full Decision Memory (G3)
-- Schema: compliance
-- Run: ssh macmini "docker exec -i bp-core-postgres psql -U breakpilot -d breakpilot_db" < control-pipeline/migrations/008_decision_events.sql

SET search_path TO compliance, public;

CREATE TABLE IF NOT EXISTS decision_events (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    decision_trace_id UUID REFERENCES decision_traces(id) ON DELETE SET NULL,
    control_uuid UUID NOT NULL,
    tenant_id UUID,

    -- Event type
    event_type VARCHAR(30) NOT NULL
        CHECK (event_type IN (
            'assessment', 'decision', 'fix_planned', 'fix_started',
            'fix_completed', 'verification', 'failure', 'exception', 'escalation'
        )),

    -- State before/after
    input_state JSONB DEFAULT '{}',
    output_state JSONB DEFAULT '{}',

    -- Details
    summary TEXT,
    actor VARCHAR(200),
    evidence_ids JSONB DEFAULT '[]',
    metadata JSONB DEFAULT '{}',

    created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_de_control ON decision_events(control_uuid);
CREATE INDEX IF NOT EXISTS idx_de_trace ON decision_events(decision_trace_id);
CREATE INDEX IF NOT EXISTS idx_de_tenant ON decision_events(tenant_id);
CREATE INDEX IF NOT EXISTS idx_de_type ON decision_events(event_type);
CREATE INDEX IF NOT EXISTS idx_de_created ON decision_events(created_at);
