import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * One-shot resync for the WHATSAPP/QUERY default template. The Phase A
 * seed shipped a short summary; UAT feedback was that Copy WhatsApp
 * on the Query surface must reproduce the current hardcoded output
 * from `generateItineraryMessage` byte-for-byte.
 *
 * The Phase A seed migration is now updated to the new body, but on
 * environments where the old body already landed (my local dev,
 * plus any preview that ran migrations before this fix) the seeded
 * row still holds the short summary. This migration overwrites those
 * rows in place — only for rows that STILL match the old body exactly
 * so ops customisations aren't clobbered.
 */
export class CommunicationTemplatesWhatsAppResync1782700000000
  implements MigrationInterface
{
  name = 'CommunicationTemplatesWhatsAppResync1782700000000';

  public async up(qr: QueryRunner): Promise<void> {
    const oldBody = `Dear {{query.guest_name}},

Greetings from {{company.name}}!

Thanks for your query. Here's a summary of the package:

*Destination:* {{destination.name}}
*Travel:* {{query.start_date}} · {{query.nights}} Nights / {{query.days}} Days
*Pax:* {{query.pax.adults}} Adults{{#if query.pax.children}} + {{query.pax.children}} Children{{/if}}
{{#if quote}}*Package Price:* {{quote.currency}} {{quote.selling_total}} (incl. VAT){{/if}}

{{#if hotels}}*Hotels*
{{#each hotels}}• {{city}}: {{hotel_name}} ({{nights}}N, {{meal_plan}})
{{/each}}{{/if}}
Reply here for any changes.

Regards,
{{company.name}}`;

    const newBody = `*{{title_emoji}} Your {{destination.name}} Itinerary {{title_emoji}}*

Hi {{query.greeting_name}},
Here's your personalized itinerary crafted for you.

📅 *{{query.date_range}}*
🧳 {{query.duration}}
👥 {{query.pax_summary}}
{{#if customer_remarks}}
_{{customer_remarks}}_
{{/if}}
{{divider}}
{{day_blocks}}

{{#if has_specials}}{{specials_block}}

{{/if}}{{divider}}
💰 *Package Price: {{price_amount}}*
_Inclusive of {{tax_label}} and selected services_

Questions? Reply here or call us — happy to help.
{{#if signature_block}}
{{signature_block}}{{/if}}`;

    await qr.query(
      `
      UPDATE communication_templates
         SET body_template = $1
       WHERE channel = 'WHATSAPP'
         AND context = 'QUERY'
         AND is_default = true
         AND is_deleted = false
         AND body_template = $2
      `,
      [newBody, oldBody],
    );
  }

  public async down(): Promise<void> {
    // No revert path — restoring the short summary as the default
    // would deliberately break parity with the current hardcoded
    // WhatsApp output, which is the exact regression we're fixing.
  }
}
