-- Migration 047: Add verification_method and category to canonical_controls
-- verification_method: How a control is verified (code_review, document, tool, hybrid)
-- category: Thematic grouping for customer-facing filters
-- Safe: only alters canonical_controls if it exists

DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'canonical_controls') THEN
        ALTER TABLE canonical_controls ADD COLUMN IF NOT EXISTS
            verification_method VARCHAR(20) DEFAULT NULL
            CHECK (verification_method IN ('code_review', 'document', 'tool', 'hybrid'));
        ALTER TABLE canonical_controls ADD COLUMN IF NOT EXISTS
            category VARCHAR(50) DEFAULT NULL;
        CREATE INDEX IF NOT EXISTS idx_cc_verification ON canonical_controls(verification_method);
        CREATE INDEX IF NOT EXISTS idx_cc_category ON canonical_controls(category);
    END IF;
END $$;

CREATE TABLE IF NOT EXISTS canonical_control_categories (
    category_id VARCHAR(50) PRIMARY KEY,
    label_de VARCHAR(100) NOT NULL,
    label_en VARCHAR(100) NOT NULL,
    sort_order INTEGER DEFAULT 0
);

INSERT INTO canonical_control_categories VALUES
    ('encryption',      'Verschluesselung & Kryptographie',       'Encryption & Cryptography', 1),
    ('authentication',  'Authentisierung & Zugriffskontrolle',    'Authentication & Access Control', 2),
    ('network',         'Netzwerksicherheit',                     'Network Security', 3),
    ('data_protection', 'Datenschutz & Datensicherheit',          'Data Protection & Security', 4),
    ('logging',         'Logging & Monitoring',                   'Logging & Monitoring', 5),
    ('incident',        'Vorfallmanagement',                      'Incident Management', 6),
    ('continuity',      'Notfall & Wiederherstellung',            'Continuity & Recovery', 7),
    ('compliance',      'Compliance & Audit',                     'Compliance & Audit', 8),
    ('supply_chain',    'Lieferkettenmanagement',                 'Supply Chain Management', 9),
    ('physical',        'Physische Sicherheit',                   'Physical Security', 10),
    ('personnel',       'Personal & Schulung',                    'Personnel & Training', 11),
    ('application',     'Anwendungssicherheit',                   'Application Security', 12),
    ('system',          'Systemhaertung & -betrieb',              'System Hardening & Operations', 13),
    ('risk',            'Risikomanagement',                       'Risk Management', 14),
    ('governance',      'Sicherheitsorganisation',                'Security Governance', 15),
    ('hardware',        'Hardware & Plattformsicherheit',         'Hardware & Platform Security', 16),
    ('identity',        'Identitaetsmanagement',                  'Identity Management', 17)
ON CONFLICT DO NOTHING;
