import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Seeds a default EMAIL and WHATSAPP template for the QUERY context
 * per tenant.
 *
 * The EMAIL/QUERY template mirrors the docx sample stakeholders
 * shared 2026-06-30 (Package Overview → Hotels → Total Price →
 * Inclusion → Terms & Conditions). It's authored as inline-styled
 * HTML so Gmail/Outlook render it faithfully when copied and pasted.
 *
 * The WHATSAPP/QUERY template is a plain-text summary — short enough
 * to send as a first-touch WhatsApp reply without truncation.
 *
 * Both rows land with is_default = true. The partial unique index
 * on the master migration allows exactly one default per (tenant,
 * channel, context), so if an existing seed run has already added
 * one it's kept and this seed is skipped.
 *
 * Idempotent — safe to re-run.
 */
export class CommunicationTemplatesSeed1782600000000 implements MigrationInterface {
  name = 'CommunicationTemplatesSeed1782600000000';

  public async up(qr: QueryRunner): Promise<void> {
    // Backfill role_permissions so existing tenants pick up the new
    // ModuleName.COMMUNICATION_TEMPLATE key without re-onboarding.
    // Admins get 'full', everyone else 'view' (so the Copy Email /
    // Copy WhatsApp buttons work for them). Idempotent — the WHERE
    // NOT EXISTS gate skips roles that already have a row.
    // access_level column is a Postgres enum
    // (none|view|create|edit|delete). Admin gets 'delete' (highest
    // hierarchy level in usePermission), everyone else gets 'view' so
    // the Copy Email/Copy WhatsApp buttons work from any role.
    await qr.query(`
      INSERT INTO role_permissions
        (role_id, module, access_level, tenant_id, created_by, updated_by)
      SELECT r.id,
             'communication_template',
             (CASE WHEN r.name = 'Admin' THEN 'delete' ELSE 'view' END)
               ::role_permissions_access_level_enum,
             r.tenant_id,
             NULL, NULL
        FROM roles r
       WHERE r.is_deleted = false
         AND NOT EXISTS (
           SELECT 1 FROM role_permissions rp
            WHERE rp.role_id = r.id
              AND rp.module = 'communication_template'
         );
    `);

    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>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 quote}}
  <h2 style="background:#1e40af;color:#fff;padding:8px 12px;border-radius:4px;font-size:16px;margin-top:20px;">Total Price</h2>
  <p style="font-size:15px;"><b>{{quote.currency}} {{quote.selling_total}}</b> (including VAT)</p>
  {{/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 emailSubject = `Your {{destination.name}} package — {{query.number}}`;

    // Matches the hardcoded `generateItineraryMessage` output on the
    // FE byte-for-byte so the switchover in Phase C causes zero
    // wording change for ops. Framing (greeting, price line, CTA,
    // sig) stays as editable tokens; the algorithmic per-day block
    // is precomputed by QueryContextResolver as day_blocks and
    // interpolated here.
    const whatsAppBody = `*{{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}}`;

    // Seed one row per tenant per (channel, context). Skips tenants
    // that already have a row in that bucket (safe re-run).
    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', 'QUERY', 'Standard Quote',
             $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 = 'QUERY'
            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', 'QUERY', 'Standard Summary',
             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 = 'QUERY'
            AND ct.is_deleted = false
       )
      `,
      [whatsAppBody],
    );
  }

  public async down(qr: QueryRunner): Promise<void> {
    // Only drop the default seeds we planted — user-added rows stay.
    await qr.query(`
      DELETE FROM communication_templates
       WHERE context = 'QUERY'
         AND name IN ('Standard Quote','Standard Summary')
         AND is_default = true;
    `);
  }
}
