-- Migration 005: Master Controls (G-pre2)
-- Schema: compliance
-- Run: ssh macmini "docker exec -i bp-core-postgres psql -U breakpilot -d breakpilot_db" < control-pipeline/migrations/005_master_controls.sql

SET search_path TO compliance, public;

CREATE TABLE IF NOT EXISTS master_controls (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    master_control_id VARCHAR(50) UNIQUE NOT NULL,
    object_group_id INTEGER NOT NULL,
    canonical_name VARCHAR(200) NOT NULL,
    phases_covered JSONB NOT NULL DEFAULT '[]',
    phase_control_count JSONB NOT NULL DEFAULT '{}',
    total_controls INTEGER DEFAULT 0,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_master_controls_group ON master_controls(object_group_id);

CREATE TABLE IF NOT EXISTS master_control_members (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    master_control_uuid UUID NOT NULL REFERENCES master_controls(id) ON DELETE CASCADE,
    control_uuid UUID NOT NULL,
    phase VARCHAR(50) NOT NULL,
    action VARCHAR(50) NOT NULL,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_mc_members_master ON master_control_members(master_control_uuid);
CREATE INDEX IF NOT EXISTS idx_mc_members_control ON master_control_members(control_uuid);
