-- Migration 063: Scoped Control Applicability
--
-- Adds 3 new JSONB columns to canonical_controls for filtering controls
-- based on customer industry, company size, and compliance scope.
--
-- v3 pipeline generates these fields automatically via LLM.
-- Old controls (v1/v2) will be backfilled separately.

ALTER TABLE canonical_controls
    ADD COLUMN IF NOT EXISTS applicable_industries JSONB DEFAULT NULL,
    ADD COLUMN IF NOT EXISTS applicable_company_size JSONB DEFAULT NULL,
    ADD COLUMN IF NOT EXISTS scope_conditions JSONB DEFAULT NULL;

-- GIN index for JSONB containment queries (e.g. applicable_industries @> '"Telekommunikation"')
CREATE INDEX IF NOT EXISTS idx_cc_applicable_industries
    ON canonical_controls USING gin (applicable_industries);

CREATE INDEX IF NOT EXISTS idx_cc_applicable_company_size
    ON canonical_controls USING gin (applicable_company_size);

COMMENT ON COLUMN canonical_controls.applicable_industries IS 'Industries this control applies to, e.g. ["all"] or ["Telekommunikation", "Energie"]. NULL = not yet classified.';
COMMENT ON COLUMN canonical_controls.applicable_company_size IS 'Company sizes this control applies to, e.g. ["all"] or ["medium", "large", "enterprise"]. NULL = not yet classified.';
COMMENT ON COLUMN canonical_controls.scope_conditions IS 'Optional scope conditions, e.g. {"requires_any": ["uses_ai"], "description": "..."}. NULL = no conditions.';
