import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Rewrites the MOVEMENT_SUPPLIER default template to the "wrapper +
 * service_body" pattern and seeds a MOVEMENT_CUSTOMER default in the
 * same shape.
 *
 * Rationale (stakeholder call 2026-07-01):
 *   - Per-activity content (Dubai City Tour inclusions, Desert Safari
 *     safety rules, Burj Khalifa restrictions) now lives on the
 *     activity/transport_service masters — new columns
 *     customer_whatsapp_body / supplier_whatsapp_body (migration
 *     1783100000000).
 *   - The Communication Templates rows hold ONLY the wrapper — greeting,
 *     row-metadata (guest, date, times, transfer type), and closing.
 *     A single {{service_body}} token drops the master's copy in.
 *   - Ops maintains the per-activity body from the Activities admin
 *     page (one place), and changes the greeting / footer once from
 *     Settings → Templates.
 *
 * Idempotent: overwrites the existing MOVEMENT_SUPPLIER default only
 * when the body matches the previous Phase D2a seed exactly (so ops
 * customisations aren't clobbered). MOVEMENT_CUSTOMER gets seeded
 * for tenants that don't already have a row.
 */
export class CommunicationTemplatesMovementWrappers1783200000000
  implements MigrationInterface
{
  name = 'CommunicationTemplatesMovementWrappers1783200000000';

  public async up(qr: QueryRunner): Promise<void> {
    // ── Previous MOVEMENT_SUPPLIER body from Phase D2a (1783000).
    // Used as the WHERE-clause match so we only overwrite the untouched
    // default, not ops customisations.
    const oldSupplierBody = `TRANSFER'S SCHEDULE FOR {{date_upper}}

GUEST NAME: MR. {{guest_name_upper}}
SERVICE: {{service_upper}}

PAX: {{pax_line}}

PICKUP LOCATION: {{pickup_location}}
DROP LOCATION: {{drop_location}}
PICKUP TIME: {{pickup_time_12h}}
RETURN PICKUP TIME: {{return_time_12h}}
TRIP COORDINATOR: {{trip_coordinator.label}}
TRANSFER TYPE: {{transfer_type}}

REMARKS: {{remarks}}

{{footer_line}}`;

    // ── New MOVEMENT_SUPPLIER wrapper. The row-metadata block (guest,
    // times, transfer type) is preserved so the sample from 2026-07-01
    // still reads faithfully; {{service_body}} slots in the master's
    // supplier_whatsapp_body if one is set.
    const newSupplierBody = `TRANSFER'S SCHEDULE FOR {{date_upper}}

GUEST NAME: MR. {{guest_name_upper}}
SERVICE: {{service_upper}}

PAX: {{pax_line}}

PICKUP LOCATION: {{pickup_location}}
DROP LOCATION: {{drop_location}}
PICKUP TIME: {{pickup_time_12h}}
RETURN PICKUP TIME: {{return_time_12h}}
TRIP COORDINATOR: {{trip_coordinator.label}}
TRANSFER TYPE: {{transfer_type}}
{{#if service_body}}

{{service_body}}
{{/if}}

REMARKS: {{remarks}}

{{footer_line}}`;

    // ── MOVEMENT_CUSTOMER wrapper. Same shape (wrapper + service_body)
    // authored for the guest-facing greeting/closing that ops uses on
    // "reminder before pickup" WhatsApps. Includes the phone-signal PS
    // as a stock line so ops doesn't have to retype it per service.
    const customerBody = `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}}`;

    // Overwrite the MOVEMENT_SUPPLIER default in place — only when
    // it still matches the Phase D2a body verbatim (idempotent safety).
    await qr.query(
      `UPDATE communication_templates
          SET body_template = $1
        WHERE channel = 'WHATSAPP'
          AND context = 'MOVEMENT_SUPPLIER'
          AND is_default = true
          AND is_deleted = false
          AND body_template = $2`,
      [newSupplierBody, oldSupplierBody],
    );

    // Seed the MOVEMENT_CUSTOMER default per tenant. Idempotent — skips
    // tenants that already have a row in this bucket.
    await qr.query(
      `INSERT INTO communication_templates
         (tenant_id, channel, context, name, subject, body_template,
          is_default, is_active)
       SELECT DISTINCT t.tenant_id, 'WHATSAPP', 'MOVEMENT_CUSTOMER',
              'Standard Customer Reminder',
              NULL, $1, true, true
         FROM tenant_settings t
        WHERE NOT EXISTS (
          SELECT 1 FROM communication_templates ct
           WHERE ct.tenant_id = t.tenant_id
             AND ct.channel = 'WHATSAPP'
             AND ct.context = 'MOVEMENT_CUSTOMER'
             AND ct.is_deleted = false
        )`,
      [customerBody],
    );
  }

  public async down(qr: QueryRunner): Promise<void> {
    await qr.query(`
      DELETE FROM communication_templates
       WHERE channel = 'WHATSAPP'
         AND context = 'MOVEMENT_CUSTOMER'
         AND name = 'Standard Customer Reminder'
         AND is_default = true;
    `);
    // Not reverting the supplier body — the wrapper form is a strict
    // superset (adds an {{#if service_body}} block), so going back
    // would remove usable content.
  }
}
