import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Injects a "COLLECT AT SERVICE" block into the two default MOVEMENT
 * wrapper templates (WHATSAPP × MOVEMENT_SUPPLIER + MOVEMENT_CUSTOMER)
 * so ops-set cash-at-service collections show up automatically on the
 * driver's / guest's message.
 *
 * The block uses the tokens surfaced by MovementSupplierContext /
 * MovementCustomerContext resolvers:
 *   payment_collection_required — {{#if}} gate (falsy → collapses)
 *   payment_collection_amount   — "125.00"
 *   payment_collection_currency — "AED" (alphabetic code from currencies.code)
 *   payment_collection_status   — 'PENDING' | 'COLLECTED'
 *
 * Idempotency
 * - We match on `body_template NOT LIKE '%payment_collection_required%'`
 *   so tenants who already ran this migration (or hand-added the block)
 *   are skipped.
 * - No prior-body allowlist: appending is safe on any body; a tenant
 *   with a heavily customised template just gets the block tacked on
 *   the end and can re-order it in Settings.
 *
 * Appended at the end (above the footer_line) — the block collapses to
 * nothing on rows without a collection, so bookings that don't use
 * this feature see zero visual noise.
 */
export class CommunicationTemplatesPaymentCollectionBlock1785300000000
  implements MigrationInterface
{
  name = 'CommunicationTemplatesPaymentCollectionBlock1785300000000';

  public async up(qr: QueryRunner): Promise<void> {
    // Supplier — surface the required cash-in-hand amount so the
    // driver / supplier knows to collect on delivery.
    const supplierBlock = [
      '',
      '{{#if payment_collection_required}}',
      '💰 *COLLECT AT SERVICE:* {{payment_collection_amount}} {{payment_collection_currency}} ({{payment_collection_status}})',
      '{{/if}}',
    ].join('\n');

    // Customer — reassures the guest what's expected on-site.
    const customerBlock = [
      '',
      '{{#if payment_collection_required}}',
      '💰 *Please have {{payment_collection_amount}} {{payment_collection_currency}} ready in cash at the time of service.*',
      '{{/if}}',
    ].join('\n');

    // Insert before the footer_line token so the block sits above the
    // "This is an automated message" tail. If footer_line isn't in the
    // body (unusual — hand-edited beyond recognition), just append.
    await qr.query(
      `UPDATE communication_templates
          SET body_template = CASE
               WHEN position('{{footer_line}}' IN body_template) > 0 THEN
                 replace(body_template, '{{footer_line}}', $1 || '{{footer_line}}')
               ELSE
                 body_template || $1
             END
        WHERE channel = 'WHATSAPP'
          AND context = 'MOVEMENT_SUPPLIER'
          AND is_default = true
          AND is_deleted = false
          AND body_template NOT LIKE '%payment_collection_required%'`,
      [supplierBlock + '\n'],
    );

    await qr.query(
      `UPDATE communication_templates
          SET body_template = CASE
               WHEN position('{{footer_line}}' IN body_template) > 0 THEN
                 replace(body_template, '{{footer_line}}', $1 || '{{footer_line}}')
               ELSE
                 body_template || $1
             END
        WHERE channel = 'WHATSAPP'
          AND context = 'MOVEMENT_CUSTOMER'
          AND is_default = true
          AND is_deleted = false
          AND body_template NOT LIKE '%payment_collection_required%'`,
      [customerBlock + '\n'],
    );
  }

  public async down(qr: QueryRunner): Promise<void> {
    // Best-effort strip: remove exact block if present. Won't undo any
    // tenant hand-edits inside the block.
    const supplierBlock = [
      '',
      '{{#if payment_collection_required}}',
      '💰 *COLLECT AT SERVICE:* {{payment_collection_amount}} {{payment_collection_currency}} ({{payment_collection_status}})',
      '{{/if}}',
      '',
    ].join('\n');
    const customerBlock = [
      '',
      '{{#if payment_collection_required}}',
      '💰 *Please have {{payment_collection_amount}} {{payment_collection_currency}} ready in cash at the time of service.*',
      '{{/if}}',
      '',
    ].join('\n');

    await qr.query(
      `UPDATE communication_templates
          SET body_template = replace(body_template, $1, '')
        WHERE channel = 'WHATSAPP'
          AND context = 'MOVEMENT_SUPPLIER'
          AND is_default = true
          AND is_deleted = false`,
      [supplierBlock],
    );
    await qr.query(
      `UPDATE communication_templates
          SET body_template = replace(body_template, $1, '')
        WHERE channel = 'WHATSAPP'
          AND context = 'MOVEMENT_CUSTOMER'
          AND is_default = true
          AND is_deleted = false`,
      [customerBlock],
    );
  }
}
