WITH ins_template AS (
    INSERT INTO hdb_communication_templates (
        template_id,
        template_name,
        template_key,
        sandbox_template_id,
        template_type,
        category,
        template_usage_type,
        template_access_key,
        program_id,
        is_enabled,
        display_order,
        created_at,
        updated_at
    )
    SELECT
        m.template_id,
        m.template_name,
        'TAT_PAYMENT_LINK_WHATSAPP',
        m.sandbox_template_id,
        'whatsapp'::communication_type_enum,
        'payment_link'::communication_category_enum,
        'general'::template_usage_type_enum,
        'PAYMENT_LINK_WATI_SEEKER'::communication_template_access_key_enum,
        p.id,
        true,
        m.display_order,
        CURRENT_TIMESTAMP,
        CURRENT_TIMESTAMP
    FROM communication_templates_master m
    CROSS JOIN program_v1 p
    WHERE m.template_key = 'TAT_PAYMENT_LINK_WHATSAPP'
      AND m.template_type = 'whatsapp'
      AND p.deleted_at IS NULL
      AND p.program_type_id = (
          SELECT id
          FROM program_type_v1
          WHERE key = 'PT_TAT'
      )
      AND NOT EXISTS (
          SELECT 1
          FROM hdb_communication_templates h
          WHERE h.program_id = p.id
            AND h.template_key = 'TAT_PAYMENT_LINK_WHATSAPP'
            AND h.template_type = 'whatsapp'
            AND h.deleted_at IS NULL
      )
    RETURNING id
)
INSERT INTO merge_info_answer_location_map (
    key_name,
    template_id,
    is_common,
    source_table,
    source_column,
    data_type,
    format_type,
    is_nullable,
    is_active,
    created_at,
    updated_at
)
SELECT
    mf.key_name,
    t.id,
    false,
    mf.source_table,
    mf.source_column,
    mf.data_type,
    mf.format_type,
    mf.is_nullable,
    true,
    CURRENT_TIMESTAMP,
    CURRENT_TIMESTAMP
FROM ins_template t
CROSS JOIN (
    VALUES
        ('reg_name',   'hdb_program_registration', 'full_name',            'string', NULL::varchar, false),
        ('batch_name', 'computed',                 'getProgramField:name', 'string', NULL::varchar, false),
        ('link',       'computed',                 'generatePaymentLink',  'string', 'url',         false),
        ('reg_mobile', 'hdb_program_registration', 'mobile_number',        'string', NULL::varchar, false),
        ('reg_email',  'hdb_program_registration', 'email_address',        'string', NULL::varchar, false),
        ('reg_rm',     'computed',                 'getRmContactUserName', 'string', NULL::varchar, true)
) AS mf(key_name, source_table, source_column, data_type, format_type, is_nullable);