-- Migration 021: Training Blocks — Generate training modules from Canonical Controls
-- Links block configs (filter criteria) to canonical controls, creating modules automatically.
-- Uses target_audience, category, severity, and domain (control_id prefix) for filtering.

BEGIN;

CREATE TABLE IF NOT EXISTS training_block_configs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL,
    name VARCHAR(255) NOT NULL,
    description TEXT,
    domain_filter VARCHAR(10),              -- "AUTH", "CRYP", etc. NULL=all domains
    category_filter VARCHAR(50),            -- "authentication", "encryption", etc. NULL=all
    severity_filter VARCHAR(20),            -- "high", "critical", etc. NULL=all
    target_audience_filter VARCHAR(20),     -- "enterprise", "authority", "provider", "all". NULL=all
    regulation_area VARCHAR(20) NOT NULL,
    module_code_prefix VARCHAR(10) NOT NULL,
    frequency_type VARCHAR(20) DEFAULT 'annual',
    duration_minutes INT DEFAULT 45,
    pass_threshold INT DEFAULT 70,
    max_controls_per_module INT DEFAULT 20,
    is_active BOOLEAN DEFAULT TRUE,
    last_generated_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE(tenant_id, name)
);

CREATE TABLE IF NOT EXISTS training_block_control_links (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    block_config_id UUID NOT NULL REFERENCES training_block_configs(id) ON DELETE CASCADE,
    module_id UUID NOT NULL REFERENCES training_modules(id) ON DELETE CASCADE,
    control_id VARCHAR(20) NOT NULL,
    control_title VARCHAR(255),
    control_objective TEXT,
    control_requirements JSONB DEFAULT '[]',
    sort_order INT DEFAULT 0,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_tbc_tenant ON training_block_configs(tenant_id);
CREATE INDEX IF NOT EXISTS idx_tbc_active ON training_block_configs(tenant_id, is_active);
CREATE INDEX IF NOT EXISTS idx_tbcl_block ON training_block_control_links(block_config_id);
CREATE INDEX IF NOT EXISTS idx_tbcl_module ON training_block_control_links(module_id);
CREATE INDEX IF NOT EXISTS idx_tbcl_control ON training_block_control_links(control_id);

COMMIT;
