import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Upgrades the MOVEMENT WhatsApp templates from the single-state
 * "please collect" block (1785300000000) to a state-aware pair:
 *
 *   PENDING   → "💰 please have X ready"     (customer)
 *               "💰 COLLECT AT SERVICE: X"    (supplier)
 *   COLLECTED → "✅ thank you — X received"   (customer receipt)
 *               "✅ CASH COLLECTED: X"        (supplier confirmation)
 *
 * Uses the two new booleans emitted by
 * MovementCustomer/SupplierContextResolver
 *   payment_collection_pending
 *   payment_collection_collected
 * so the wrapper can nest a second {{#if}} inside the existing
 * required gate. Renderer supports balanced nested blocks.
 *
 * Idempotency
 * - Replaces the exact old block from 1785300000000. Templates that
 *   already contain the new markers (`payment_collection_pending`)
 *   are skipped so a re-run is a no-op.
 * - Tenants who hand-edited the old block are also skipped — the
 *   exact-match `replace()` returns the body unchanged if the old
 *   block isn't found byte-for-byte.
 */
export class CommunicationTemplatesPaymentCollectionStates1785400000000
  implements MigrationInterface
{
  name = 'CommunicationTemplatesPaymentCollectionStates1785400000000';

  public async up(qr: QueryRunner): Promise<void> {
    const oldSupplierBlock = [
      '',
      '{{#if payment_collection_required}}',
      '💰 *COLLECT AT SERVICE:* {{payment_collection_amount}} {{payment_collection_currency}} ({{payment_collection_status}})',
      '{{/if}}',
      '',
    ].join('\n');

    const newSupplierBlock = [
      '',
      '{{#if payment_collection_required}}',
      '{{#if payment_collection_pending}}',
      '💰 *COLLECT AT SERVICE:* {{payment_collection_amount}} {{payment_collection_currency}} from guest',
      '{{/if}}',
      '{{#if payment_collection_collected}}',
      '✅ *CASH COLLECTED:* {{payment_collection_actual_amount}} {{payment_collection_currency}} — noted in system',
      '{{/if}}',
      '{{/if}}',
      '',
    ].join('\n');

    const oldCustomerBlock = [
      '',
      '{{#if payment_collection_required}}',
      '💰 *Please have {{payment_collection_amount}} {{payment_collection_currency}} ready in cash at the time of service.*',
      '{{/if}}',
      '',
    ].join('\n');

    const newCustomerBlock = [
      '',
      '{{#if payment_collection_required}}',
      '{{#if payment_collection_pending}}',
      '💰 *Please have {{payment_collection_amount}} {{payment_collection_currency}} ready in cash at the time of service.*',
      '{{/if}}',
      '{{#if payment_collection_collected}}',
      '✅ *Thank you — {{payment_collection_actual_amount}} {{payment_collection_currency}} received. Your payment has been recorded.*',
      '{{/if}}',
      '{{/if}}',
      '',
    ].join('\n');

    await qr.query(
      `UPDATE communication_templates
          SET body_template = replace(body_template, $1, $2)
        WHERE channel = 'WHATSAPP'
          AND context = 'MOVEMENT_SUPPLIER'
          AND is_default = true
          AND is_deleted = false
          AND body_template LIKE '%payment_collection_required%'
          AND body_template NOT LIKE '%payment_collection_pending%'`,
      [oldSupplierBlock, newSupplierBlock],
    );

    await qr.query(
      `UPDATE communication_templates
          SET body_template = replace(body_template, $1, $2)
        WHERE channel = 'WHATSAPP'
          AND context = 'MOVEMENT_CUSTOMER'
          AND is_default = true
          AND is_deleted = false
          AND body_template LIKE '%payment_collection_required%'
          AND body_template NOT LIKE '%payment_collection_pending%'`,
      [oldCustomerBlock, newCustomerBlock],
    );
  }

  public async down(qr: QueryRunner): Promise<void> {
    // Best-effort reverse: swap the new dual-state block back to the
    // single-state block from 1785300000000. Won't restore any tenant
    // hand-edits between the two migrations.
    const oldSupplierBlock = [
      '',
      '{{#if payment_collection_required}}',
      '💰 *COLLECT AT SERVICE:* {{payment_collection_amount}} {{payment_collection_currency}} ({{payment_collection_status}})',
      '{{/if}}',
      '',
    ].join('\n');
    const newSupplierBlock = [
      '',
      '{{#if payment_collection_required}}',
      '{{#if payment_collection_pending}}',
      '💰 *COLLECT AT SERVICE:* {{payment_collection_amount}} {{payment_collection_currency}} from guest',
      '{{/if}}',
      '{{#if payment_collection_collected}}',
      '✅ *CASH COLLECTED:* {{payment_collection_actual_amount}} {{payment_collection_currency}} — noted in system',
      '{{/if}}',
      '{{/if}}',
      '',
    ].join('\n');
    const oldCustomerBlock = [
      '',
      '{{#if payment_collection_required}}',
      '💰 *Please have {{payment_collection_amount}} {{payment_collection_currency}} ready in cash at the time of service.*',
      '{{/if}}',
      '',
    ].join('\n');
    const newCustomerBlock = [
      '',
      '{{#if payment_collection_required}}',
      '{{#if payment_collection_pending}}',
      '💰 *Please have {{payment_collection_amount}} {{payment_collection_currency}} ready in cash at the time of service.*',
      '{{/if}}',
      '{{#if payment_collection_collected}}',
      '✅ *Thank you — {{payment_collection_actual_amount}} {{payment_collection_currency}} received. Your payment has been recorded.*',
      '{{/if}}',
      '{{/if}}',
      '',
    ].join('\n');

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