-- Migration 160: Backfill missing body text in auto-created SAG descriptions
-- Fills existing cases where description only contains metadata and no actual email content.

WITH candidates AS (
    SELECT
        s.id AS sag_id,
        s.beskrivelse,
        COALESCE(
            NULLIF(BTRIM(em.body_text), ''),
            NULLIF(
                BTRIM(
                    REGEXP_REPLACE(
                        REGEXP_REPLACE(COALESCE(em.body_html, ''), '<(style|script)[^>]*>.*?</\1>', ' ', 'gis'),
                        '<[^>]+>',
                        ' ',
                        'g'
                    )
                ),
                ''
            )
        ) AS recovered_body
    FROM sag_sager s
    JOIN sag_emails se ON se.sag_id = s.id
    JOIN email_messages em ON em.id = se.email_id
    WHERE s.beskrivelse LIKE 'Auto-oprettet fra email%'
      AND COALESCE(
            NULLIF(
                BTRIM(
                    REGEXP_REPLACE(
                        COALESCE(s.beskrivelse, ''),
                        '(?s)^Auto-oprettet fra email\s*\nFra:[^\n]*\nMessage-ID:[^\n]*\n*',
                        ''
                    )
                ),
                ''
            ),
            ''
          ) = ''
), dedup AS (
    SELECT DISTINCT ON (sag_id)
        sag_id,
        recovered_body
    FROM candidates
    WHERE recovered_body IS NOT NULL
      AND recovered_body <> ''
    ORDER BY sag_id
)
UPDATE sag_sager s
SET beskrivelse = CONCAT_WS(E'\n\n', BTRIM(COALESCE(s.beskrivelse, '')), dedup.recovered_body)
FROM dedup
WHERE s.id = dedup.sag_id;
