import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Seeds the default WHATSAPP/MOVEMENT_SUPPLIER template per tenant.
 *
 * Body matches the stakeholder sample 2026-07-01 verbatim — uppercase
 * transfer schedule format sent to the assigned supplier's WhatsApp
 * on the Movement Dashboard row. Every dynamic value maps to a token
 * emitted by MovementSupplierContextResolver.
 *
 * Idempotent: skips tenants that already have a default row in this
 * bucket so ops customisations aren't stomped.
 */
export class CommunicationTemplatesMovementSupplierSeed1783000000000
  implements MigrationInterface
{
  name = 'CommunicationTemplatesMovementSupplierSeed1783000000000';

  public async up(qr: QueryRunner): Promise<void> {
    const body = `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}}`;

    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_SUPPLIER',
             'Standard Supplier Notice',
             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_SUPPLIER'
            AND ct.is_deleted = false
       )
      `,
      [body],
    );
  }

  public async down(qr: QueryRunner): Promise<void> {
    await qr.query(`
      DELETE FROM communication_templates
       WHERE channel = 'WHATSAPP'
         AND context = 'MOVEMENT_SUPPLIER'
         AND name = 'Standard Supplier Notice'
         AND is_default = true;
    `);
  }
}
