-- ============================================================
-- Update: TAT Common Invite — WhatsApp (WATI) template_id bumped
-- from 'tat_common_invite_v2' to 'tat_common_invite_v3'.
--
-- The template lives in two places:
--   1. communication_templates_master  (PT_TAT master row)
--   2. hdb_communication_templates      (per-program cloned rows,
--      see PART 2 of 32_common-invite-template-seed.sql)
--
-- Both must be updated so existing programs pick up the new template id.
-- Idempotent: matching on the old value means re-runs are no-ops.
-- ============================================================

-- 1. Master template
UPDATE communication_templates_master
SET
    template_id = 'tat_common_invite_v3',
    updated_at = CURRENT_TIMESTAMP
WHERE template_key = 'TAT_COMMON_INVITE_WATI_SEEKER'
  AND template_type = 'whatsapp'
  AND program_type_id = (SELECT id FROM program_type_v1 WHERE key = 'PT_TAT')
  AND template_id = 'tat_common_invite_v2';

-- 2. Per-program cloned rows (inner TAT tables)
UPDATE hdb_communication_templates hct
SET
    template_id = 'tat_common_invite_v3',
    updated_at = CURRENT_TIMESTAMP
FROM program_v1 p
INNER JOIN program_type_v1 pt ON p.program_type_id = pt.id
WHERE hct.program_id = p.id
  AND pt.key = 'PT_TAT'
  AND hct.template_key::text = 'TAT_COMMON_INVITE_WATI_SEEKER'
  AND hct.template_type = 'whatsapp'
  AND hct.template_id = 'tat_common_invite_v2';

-- ------------------------------------------------
-- Verification
-- ------------------------------------------------
SELECT template_key, template_access_key, template_id, is_active
FROM communication_templates_master
WHERE template_key = 'TAT_COMMON_INVITE_WATI_SEEKER';

SELECT hct.template_key::text AS template_key, hct.program_id, hct.template_id
FROM hdb_communication_templates hct
WHERE hct.template_key::text = 'TAT_COMMON_INVITE_WATI_SEEKER'
ORDER BY hct.program_id;
