-- Migration 023: New DE Document Templates with {{#IF}} Block Syntax
-- ============================================================
-- This migration adds 4 new German document templates that use
-- the {{#IF CONDITION}}...{{/IF}} conditional block syntax
-- introduced in Template-Spec v1 Phase C.
--
-- Templates inserted (via Python script: scripts/apply_templates_023.py):
--
--   document_type       | language | title
--   ────────────────────┼──────────┼─────────────────────────────────────────────
--   cookie_banner       | de       | Cookie-Banner Texte v2 (DSGVO/TDDDG, IF-Blöcke)
--   privacy_policy      | de       | Datenschutzerklärung (DSGVO-konform, IF-Blöcke)
--   agb                 | de       | AGB SaaS/Cloud DE (B2B/B2C, IF-Blöcke)
--   impressum           | de       | Impressum DE (DDG § 5, IF-Blöcke)
--
-- Conditional syntax supported in templates:
--   {{#IF CONDITION}}...{{/IF}}
--   {{#IF_NOT CONDITION}}...{{/IF_NOT}}
--   {{#IF_ANY COND_A COND_B COND_C}}...{{/IF_ANY}}
--
-- Boolean conditions are evaluated by applyConditionalBlocks() in ruleEngine.ts
-- using the combined boolCtx from buildBoolContext(ctx, computedFlags).
--
-- No schema changes required — templates are inserted into the existing
-- public.compliance_legal_templates table.
--
-- Run the Python migration script:
--   docker cp scripts/apply_templates_023.py bp-compliance-backend:/tmp/
--   docker exec bp-compliance-backend python3 /tmp/apply_templates_023.py
-- ============================================================

-- Verify templates were inserted (run after script):
SELECT
    document_type,
    language,
    title,
    version,
    is_active,
    LENGTH(content) AS content_length,
    array_length(placeholders, 1) AS placeholder_count,
    created_at
FROM public.compliance_legal_templates
WHERE document_type IN ('cookie_banner', 'privacy_policy', 'agb', 'impressum')
  AND language = 'de'
ORDER BY document_type;

-- Count {{#IF}} blocks per template:
SELECT
    document_type,
    title,
    (LENGTH(content) - LENGTH(REPLACE(content, '{{#IF ', ''))) / LENGTH('{{#IF ') AS if_block_count
FROM public.compliance_legal_templates
WHERE document_type IN ('cookie_banner', 'privacy_policy', 'agb', 'impressum')
  AND language = 'de';
