import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Phase D2 — split the MOVEMENT context on communication_templates
 * into MOVEMENT_CUSTOMER + MOVEMENT_SUPPLIER.
 *
 * The Movement Dashboard row has two distinct outbound WhatsApp
 * shortcuts — one that goes to the guest (customer) about their
 * pickup, and one that goes to the assigned supplier about the
 * job. They read very differently, so treating them as one bucket
 * would force ops to name templates awkwardly ("Driver notice —
 * Customer variant" etc.). Two contexts keeps the FE picker
 * scoped naturally: the Copy WA / Share WA buttons on each shortcut
 * fetch only the templates for their surface.
 *
 * The old MOVEMENT literal is dropped from the CHECK constraint;
 * any existing rows (none in prod today) are migrated across —
 * a NULL-safe rewrite renames MOVEMENT → MOVEMENT_SUPPLIER by
 * default so ops don't lose whatever they'd started drafting.
 */
export class CommunicationTemplatesMovementContexts1782900000000
  implements MigrationInterface
{
  name = 'CommunicationTemplatesMovementContexts1782900000000';

  public async up(qr: QueryRunner): Promise<void> {
    // The Phase A migration wrote the CHECK inline with an explicit
    // name, but Postgres normalises constraint definitions — the
    // stored name can drift when TypeORM later regenerates or when
    // the constraint is dropped/re-added by an earlier migration.
    // Discover the current CHECK on `context` via pg_constraint and
    // drop by the actual name so this migration is resilient across
    // environments.
    await qr.query(`
      DO $$
      DECLARE v_name text;
      BEGIN
        SELECT conname INTO v_name
          FROM pg_constraint
         WHERE conrelid = 'communication_templates'::regclass
           AND contype = 'c'
           AND pg_get_constraintdef(oid) ILIKE '%context%';
        IF v_name IS NOT NULL THEN
          EXECUTE format(
            'ALTER TABLE communication_templates DROP CONSTRAINT %I',
            v_name
          );
        END IF;
      END $$;
    `);
    await qr.query(
      `UPDATE communication_templates
          SET context = 'MOVEMENT_SUPPLIER'
        WHERE context = 'MOVEMENT';`,
    );
    await qr.query(
      `ALTER TABLE communication_templates
         ADD CONSTRAINT communication_templates_context_chk
           CHECK (context IN ('QUERY','BOOKING','MOVEMENT_CUSTOMER','MOVEMENT_SUPPLIER'));`,
    );
  }

  public async down(qr: QueryRunner): Promise<void> {
    await qr.query(`
      DO $$
      DECLARE v_name text;
      BEGIN
        SELECT conname INTO v_name
          FROM pg_constraint
         WHERE conrelid = 'communication_templates'::regclass
           AND contype = 'c'
           AND pg_get_constraintdef(oid) ILIKE '%context%';
        IF v_name IS NOT NULL THEN
          EXECUTE format(
            'ALTER TABLE communication_templates DROP CONSTRAINT %I',
            v_name
          );
        END IF;
      END $$;
    `);
    await qr.query(
      `UPDATE communication_templates
          SET context = 'MOVEMENT'
        WHERE context IN ('MOVEMENT_CUSTOMER','MOVEMENT_SUPPLIER');`,
    );
    await qr.query(
      `ALTER TABLE communication_templates
         ADD CONSTRAINT communication_templates_context_chk
           CHECK (context IN ('QUERY','BOOKING','MOVEMENT'));`,
    );
  }
}
