import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Swaps the hardcoded "Good Afternoon" in the MOVEMENT_CUSTOMER
 * wrapper for a {{greeting_time_of_day}} token so the greeting
 * matches the destination's local time (Morning / Afternoon /
 * Evening / Night).
 *
 * The token is emitted by MovementCustomerContextResolver +
 * MovementSupplierContextResolver from the destination's timezone
 * column via Intl.DateTimeFormat. Fallback bucketing (server UTC)
 * kicks in when a destination has no timezone set.
 *
 * Idempotent: overwrites only the exact previous Phase D2b body
 * (name = "Standard Customer Reminder") so ops customisations
 * aren't clobbered.
 */
export class CommunicationTemplatesGreetingTimeOfDay1783300000000
  implements MigrationInterface
{
  name = 'CommunicationTemplatesGreetingTimeOfDay1783300000000';

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

Tomorrow ({{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 newCustomerBody = `Hello! Good {{greeting_time_of_day}}, {{guest_name_titled}},

Tomorrow ({{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}}`;

    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`,
      [newCustomerBody, oldCustomerBody],
    );
  }

  public async down(): Promise<void> {
    // No revert — going back to the hardcoded greeting would be a
    // deliberate regression on the destination-timezone-aware output.
  }
}
