import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Seeds the two default BOOKING-context templates per tenant:
 * an email confirmation matching the docx sample layout (subject
 * swaps query_number → booking_number) and a WhatsApp confirmation
 * that mirrors generateItineraryMessage's output for the booking
 * surface — same day_blocks/signature/tax_label token set the
 * QUERY seed uses, only the copy changes ("Here's your confirmed
 * trip itinerary" vs "…personalized itinerary crafted for you").
 *
 * Idempotent — skips tenants that already have a default row.
 */
export class CommunicationTemplatesBookingSeed1782800000000
  implements MigrationInterface
{
  name = 'CommunicationTemplatesBookingSeed1782800000000';

  public async up(qr: QueryRunner): Promise<void> {
    const emailSubject = `Booking confirmed — {{booking.number}}`;

    const emailBody = `<!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}}

  <h2 style="background:#065f46;color:#fff;padding:8px 12px;border-radius:4px;font-size:16px;margin-top:20px;">Total Price</h2>
  <p style="font-size:15px;"><b>{{price_amount}}</b> (including {{tax_label}})</p>

  {{#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>`;

    // WhatsApp body — matches generateItineraryMessage's booking
    // branch (only greeting_text differs from the QUERY seed).
    const whatsAppBody = `*{{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}}`;

    await qr.query(
      `
      INSERT INTO communication_templates
        (tenant_id, channel, context, name, subject, body_template,
         is_default, is_active)
      SELECT DISTINCT t.tenant_id, 'EMAIL', 'BOOKING', 'Standard Confirmation',
             $1, $2, 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 = 'EMAIL' AND ct.context = 'BOOKING'
            AND ct.is_deleted = false
       )
      `,
      [emailSubject, emailBody],
    );

    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', 'BOOKING', 'Standard Confirmation',
             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 = 'BOOKING'
            AND ct.is_deleted = false
       )
      `,
      [whatsAppBody],
    );
  }

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