-- Migration 137: Template-Kategorisierung (Lifecycle + Functional Category)
-- ADDITIVE Aenderung an compliance_legal_templates: zwei neue Spalten
-- Keine Breaking Changes; alte Code-Pfade bleiben funktionsfaehig

-- Spalte 1: Lifecycle Stage (mehrwertig - ein Template kann fuer mehrere Phasen relevant sein)
ALTER TABLE compliance_legal_templates
  ADD COLUMN IF NOT EXISTS lifecycle_stage TEXT[] DEFAULT '{}';

-- Spalte 2: Funktionale Kategorie (einwertig)
ALTER TABLE compliance_legal_templates
  ADD COLUMN IF NOT EXISTS functional_category TEXT;

-- Index fuer Filter-Performance
CREATE INDEX IF NOT EXISTS idx_clt_lifecycle_stage ON compliance_legal_templates USING gin(lifecycle_stage);
CREATE INDEX IF NOT EXISTS idx_clt_functional_category ON compliance_legal_templates(functional_category);

-- CHECK Constraint fuer functional_category (enum-aehnlich, aber erweiterbar)
ALTER TABLE compliance_legal_templates
  DROP CONSTRAINT IF EXISTS chk_clt_functional_category;
ALTER TABLE compliance_legal_templates
  ADD CONSTRAINT chk_clt_functional_category CHECK (
    functional_category IS NULL OR functional_category IN (
      'founding_legal',
      'employment',
      'investor_funding',
      'customer_b2b',
      'customer_b2c',
      'data_protection',
      'it_security',
      'ai_governance',
      'internal_policy',
      'public_facing',
      'compliance_process',
      'finance_tax',
      'vendor_supplier'
    )
  );

-- CHECK Constraint fuer lifecycle_stage Array-Werte (validate elements)
ALTER TABLE compliance_legal_templates
  DROP CONSTRAINT IF EXISTS chk_clt_lifecycle_stage;
ALTER TABLE compliance_legal_templates
  ADD CONSTRAINT chk_clt_lifecycle_stage CHECK (
    lifecycle_stage <@ ARRAY['pre_founding','founding','startup','kmu','konzern']::TEXT[]
  );

-- Verifikation: Schema-Erweiterung
SELECT
    column_name, data_type, is_nullable, column_default
FROM information_schema.columns
WHERE table_name = 'compliance_legal_templates'
  AND column_name IN ('lifecycle_stage', 'functional_category')
ORDER BY column_name;
