import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Master seed baseline for communication_templates. Captures the
 * ops-approved template bodies (extracted from the local UAT tenant
 * on 2026-07-01) as the canonical defaults for every (channel,
 * context) bucket. Six rows: EMAIL/QUERY, EMAIL/BOOKING,
 * WHATSAPP/QUERY, WHATSAPP/BOOKING, WHATSAPP/MOVEMENT_SUPPLIER,
 * WHATSAPP/MOVEMENT_CUSTOMER.
 *
 * Idempotency contract:
 *   - Inserts a default row per tenant×bucket ONLY when no default
 *     row already exists there. Fresh tenants get the ops-approved
 *     baseline; existing tenants keep their current customisations
 *     verbatim (their edits win over any subsequent baseline change).
 *   - Same pattern the earlier bucket seeds use — see 1782600 for
 *     the original QUERY seed.
 *
 * If a tenant needs to be reset to the master baseline, ops can
 * soft-delete their current default row and rerun this migration
 * (or use the future "Reset to master seed" admin action).
 */
export class CommunicationTemplatesMasterSeed1783400000000
  implements MigrationInterface
{
  name = 'CommunicationTemplatesMasterSeed1783400000000';

  public async up(qr: QueryRunner): Promise<void> {
    const emailQuerySubject = `Your {{destination.name}} package — {{query.number}}`;
    const emailBookingSubject = `Booking confirmed — {{booking.number}}`;

    const emailQueryBody = `<!doctype html>
<div style="font-family:'Segoe UI',Arial,sans-serif;color:#0f172a;max-width:720px;margin:auto;">
  <p>Dear {{query.guest_name}},</p>
  <p><b>Greetings from {{company.name}} !!!</b></p>
  <p>Thanks for your query. Please find the below quote as per your requirement…</p>

  <h2 style="background:#1e40af;color:#fff;padding:8px 12px;border-radius:4px;font-size:16px;">Package Overview</h2>
  <table style="width:100%;border-collapse:collapse;font-size:14px;">
    <tr><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;width:180px;"><b>Trip ID</b></td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;">{{query.number}}</td></tr>
    <tr><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;"><b>Destination</b></td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;">{{destination.name}}</td></tr>
    <tr><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;"><b>Start Date</b></td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;">{{query.start_date}}</td></tr>
    <tr><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;"><b>Trip Duration</b></td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;">{{query.nights}} Nights / {{query.days}} Days</td></tr>
    <tr><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;"><b>Pax</b></td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;">{{query.pax.adults}} Adults{{#if query.pax.children}} + {{query.pax.children}} Children{{/if}}</td></tr>
    {{#if query.reference_id}}<tr><td style="padding:6px 8px;"><b>Reference ID</b></td><td style="padding:6px 8px;">#{{query.reference_id}}</td></tr>{{/if}}
  </table>

  {{#if hotels}}
  <h2 style="background:#1e40af;color:#fff;padding:8px 12px;border-radius:4px;font-size:16px;margin-top:20px;">Hotels</h2>
  <table style="width:100%;border-collapse:collapse;font-size:13px;">
    <thead>
      <tr style="background:#f1f5f9;">
        <th style="padding:6px 8px;text-align:left;border-bottom:1px solid #cbd5e1;">Nights</th>
        <th style="padding:6px 8px;text-align:left;border-bottom:1px solid #cbd5e1;">City</th>
        <th style="padding:6px 8px;text-align:left;border-bottom:1px solid #cbd5e1;">Hotel Name</th>
        <th style="padding:6px 8px;text-align:left;border-bottom:1px solid #cbd5e1;">Meal Plan</th>
        <th style="padding:6px 8px;text-align:left;border-bottom:1px solid #cbd5e1;">Accommodation</th>
      </tr>
    </thead>
    <tbody>
      {{#each hotels}}
      <tr>
        <td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;vertical-align:top;">{{check_in_date}} — {{check_out_date}} ({{nights}} nights)</td>
        <td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;vertical-align:top;">{{city}}</td>
        <td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;vertical-align:top;"><b>{{hotel_name}}</b>{{#if star_rating}} — {{star_rating}} Star{{/if}}</td>
        <td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;vertical-align:top;">{{meal_plan}}</td>
        <td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;vertical-align:top;">{{num_rooms}} × {{room_type}}</td>
      </tr>
      {{/each}}
    </tbody>
  </table>
  {{/if}}


  {{#if inclusion_by_day}}
  <h2 style="background:#1e40af;color:#fff;padding:8px 12px;border-radius:4px;font-size:16px;margin-top:20px;">Inclusion</h2>
  {{#each inclusion_by_day}}
  <p style="margin:8px 0 4px;"><b>{{day_number}}st Day ({{weekday}}, {{date}})</b></p>
  <ul style="margin:0 0 8px 20px;padding:0;font-size:14px;">
    {{#each items}}
    <li style="margin:2px 0;">{{label}}</li>
    {{/each}}
  </ul>
  {{/each}}
  {{/if}}

  {{#if terms}}
  <h2 style="background:#1e40af;color:#fff;padding:8px 12px;border-radius:4px;font-size:16px;margin-top:20px;">Terms &amp; Conditions</h2>
  <div style="font-size:13px;white-space:pre-wrap;">{{terms}}</div>
  {{/if}}

  <p style="margin-top:24px;font-size:13px;">Regards,<br/><b>{{company.name}}</b><br/>{{company.email}} · {{company.phone}}</p>
</div>`;

    const emailBookingBody = `<!doctype html>
<div style="font-family:'Segoe UI',Arial,sans-serif;color:#0f172a;max-width:720px;margin:auto;">
  <p>Dear {{query.guest_name}},</p>
  <p><b>Thanks for choosing {{company.name}} !!!</b></p>
  <p>Your booking is confirmed. Please find the full itinerary below.</p>

  <h2 style="background:#065f46;color:#fff;padding:8px 12px;border-radius:4px;font-size:16px;">Booking Overview</h2>
  <table style="width:100%;border-collapse:collapse;font-size:14px;">
    <tr><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;width:180px;"><b>Booking ID</b></td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;">{{booking.number}}</td></tr>
    <tr><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;"><b>Destination</b></td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;">{{destination.name}}</td></tr>
    <tr><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;"><b>Start Date</b></td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;">{{query.start_date}}</td></tr>
    <tr><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;"><b>Trip Duration</b></td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;">{{query.nights}} Nights / {{query.days}} Days</td></tr>
    <tr><td style="padding:6px 8px;"><b>Pax</b></td><td style="padding:6px 8px;">{{query.pax.adults}} Adults{{#if query.pax.children}} + {{query.pax.children}} Children{{/if}}</td></tr>
  </table>

  {{#if hotels}}
  <h2 style="background:#065f46;color:#fff;padding:8px 12px;border-radius:4px;font-size:16px;margin-top:20px;">Hotels</h2>
  <table style="width:100%;border-collapse:collapse;font-size:13px;">
    <thead>
      <tr style="background:#f1f5f9;">
        <th style="padding:6px 8px;text-align:left;border-bottom:1px solid #cbd5e1;">Nights</th>
        <th style="padding:6px 8px;text-align:left;border-bottom:1px solid #cbd5e1;">City</th>
        <th style="padding:6px 8px;text-align:left;border-bottom:1px solid #cbd5e1;">Hotel Name</th>
        <th style="padding:6px 8px;text-align:left;border-bottom:1px solid #cbd5e1;">Meal Plan</th>
        <th style="padding:6px 8px;text-align:left;border-bottom:1px solid #cbd5e1;">Accommodation</th>
      </tr>
    </thead>
    <tbody>
      {{#each hotels}}
      <tr>
        <td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;vertical-align:top;">{{check_in_date}} — {{check_out_date}} ({{nights}} nights)</td>
        <td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;vertical-align:top;">{{city}}</td>
        <td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;vertical-align:top;"><b>{{hotel_name}}</b>{{#if star_rating}} — {{star_rating}} Star{{/if}}</td>
        <td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;vertical-align:top;">{{meal_plan}}</td>
        <td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;vertical-align:top;">{{num_rooms}} × {{room_type}}</td>
      </tr>
      {{/each}}
    </tbody>
  </table>
  {{/if}}

  {{#if inclusion_by_day}}
  <h2 style="background:#065f46;color:#fff;padding:8px 12px;border-radius:4px;font-size:16px;margin-top:20px;">Inclusion</h2>
  {{#each inclusion_by_day}}
  <p style="margin:8px 0 4px;"><b>Day {{day_number}} ({{weekday}}, {{date}})</b></p>
  <ul style="margin:0 0 8px 20px;padding:0;font-size:14px;">
    {{#each items}}
    <li style="margin:2px 0;">{{label}}</li>
    {{/each}}
  </ul>
  {{/each}}
  {{/if}}

  {{#if terms}}
  <h2 style="background:#065f46;color:#fff;padding:8px 12px;border-radius:4px;font-size:16px;margin-top:20px;">Terms &amp; Conditions</h2>
  <div style="font-size:13px;white-space:pre-wrap;">{{terms}}</div>
  {{/if}}

  <p style="margin-top:24px;font-size:13px;">Regards,<br/><b>{{company.name}}</b><br/>{{company.email}} · {{company.phone}}</p>
</div>`;

    const whatsAppQueryBody = `*{{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}}`;

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

Hi {{query.greeting_name}},
Here's your confirmed trip itinerary.

📅 *{{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}}`;

    const whatsAppMovementSupplierBody = `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}}`;

    const whatsAppMovementCustomerBody = `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}}`;

    // Idempotent seed — inserts a default row per tenant×bucket
    // ONLY when the tenant doesn't already have one. Existing
    // customisations survive untouched. Reset-to-master needs a
    // separate admin action (out of scope for this migration).
    const buckets = [
      {
        channel: 'EMAIL',
        context: 'QUERY',
        name: 'Standard Quote',
        subject: emailQuerySubject,
        body: emailQueryBody,
      },
      {
        channel: 'EMAIL',
        context: 'BOOKING',
        name: 'Standard Confirmation',
        subject: emailBookingSubject,
        body: emailBookingBody,
      },
      {
        channel: 'WHATSAPP',
        context: 'QUERY',
        name: 'Standard Summary',
        subject: null,
        body: whatsAppQueryBody,
      },
      {
        channel: 'WHATSAPP',
        context: 'BOOKING',
        name: 'Standard Confirmation',
        subject: null,
        body: whatsAppBookingBody,
      },
      {
        channel: 'WHATSAPP',
        context: 'MOVEMENT_SUPPLIER',
        name: 'Standard Supplier Notice',
        subject: null,
        body: whatsAppMovementSupplierBody,
      },
      {
        channel: 'WHATSAPP',
        context: 'MOVEMENT_CUSTOMER',
        name: 'Standard Customer Reminder',
        subject: null,
        body: whatsAppMovementCustomerBody,
      },
    ];

    for (const b of buckets) {
      await qr.query(
        `INSERT INTO communication_templates
           (tenant_id, channel, context, name, subject, body_template,
            is_default, is_active)
         SELECT DISTINCT t.tenant_id, $1, $2, $3, $4, $5, 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 = $1
               AND ct.context = $2
               AND ct.is_default = true
               AND ct.is_deleted = false
          )`,
        [b.channel, b.context, b.name, b.subject, b.body],
      );
    }
  }

  public async down(qr: QueryRunner): Promise<void> {
    // Only drop rows that still match the exact baseline body — ops
    // customisations survive down-migration too.
    const buckets: Array<{ channel: string; context: string; name: string }> = [
      { channel: 'EMAIL', context: 'QUERY', name: 'Standard Quote' },
      { channel: 'EMAIL', context: 'BOOKING', name: 'Standard Confirmation' },
      { channel: 'WHATSAPP', context: 'QUERY', name: 'Standard Summary' },
      { channel: 'WHATSAPP', context: 'BOOKING', name: 'Standard Confirmation' },
      {
        channel: 'WHATSAPP',
        context: 'MOVEMENT_SUPPLIER',
        name: 'Standard Supplier Notice',
      },
      {
        channel: 'WHATSAPP',
        context: 'MOVEMENT_CUSTOMER',
        name: 'Standard Customer Reminder',
      },
    ];
    for (const b of buckets) {
      await qr.query(
        `DELETE FROM communication_templates
          WHERE channel = $1 AND context = $2
            AND name = $3
            AND is_default = true`,
        [b.channel, b.context, b.name],
      );
    }
  }
}
