import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Adds Supplier / Driver / Remarks lines to the MOVEMENT_CUSTOMER
 * WhatsApp default body. Each line is wrapped in {{#if …}} so it
 * collapses cleanly when the corresponding token is empty — the
 * message shape stays the same for rows where ops hasn't yet
 * assigned a supplier or driver.
 *
 * Tokens exposed by MovementCustomerContextResolver (transport
 * branch): supplier_name, supplier_phone, driver_name, driver_phone.
 * Activity + special branches leave the supplier/driver tokens
 * empty so those blocks collapse there.
 *
 * Idempotent: only overwrites rows whose current body matches the
 * exact prior default. Tenant customisations survive.
 */
export class CommunicationTemplatesCustomerSupplierDriver1783600000000
  implements MigrationInterface
{
  name = 'CommunicationTemplatesCustomerSupplierDriver1783600000000';

  public async up(qr: QueryRunner): Promise<void> {
    const oldBody = `Hello! Good {{greeting_time_of_day}}, {{guest_name_titled}},

On ({{date_upper}}) we would like to remind you that your {{service_upper}} is scheduled.

*Pickup Time:* {{pickup_time_12h}}
{{#if pickup_location}}*Pickup Location:* {{pickup_location}}
{{/if}}{{#if service_body}}

{{service_body}}
{{/if}}

‼️ Please ensure your phone's 📱 data connection is active 📶 or that you have good Wi-Fi at the time of pickup. If you have an alternative contact number, kindly share it with us so we can serve you better. ‼️

Thank you for choosing us. We hope you have a pleasant experience!

{{footer_line}}`;

    const newBody = `Hello! Good {{greeting_time_of_day}}, {{guest_name_titled}},

On ({{date_upper}}) we would like to remind you that your {{service_upper}} is scheduled.

*Pickup Time:* {{pickup_time_12h}}
{{#if pickup_location}}*Pickup Location:* {{pickup_location}}
{{/if}}{{#if supplier_name}}*Supplier:* {{supplier_name}}{{#if supplier_phone}} — {{supplier_phone}}{{/if}}
{{/if}}{{#if driver_name}}*Driver:* {{driver_name}}{{#if driver_phone}} — {{driver_phone}}{{/if}}
{{/if}}{{#if remarks}}*Remarks:* {{remarks}}
{{/if}}{{#if service_body}}

{{service_body}}
{{/if}}

‼️ Please ensure your phone's 📱 data connection is active 📶 or that you have good Wi-Fi at the time of pickup. If you have an alternative contact number, kindly share it with us so we can serve you better. ‼️

Thank you for choosing us. We hope you have a pleasant experience!

{{footer_line}}`;

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

  public async down(): Promise<void> {
    // No revert — the added lines are conditional and non-breaking.
  }
}
