import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Movement Dashboard Activity / Special tabs get their own WhatsApp
 * templates (Customer + Supplier each):
 *   MOVEMENT_ACTIVITY_CUSTOMER · MOVEMENT_ACTIVITY_SUPPLIER
 *   MOVEMENT_SPECIAL_CUSTOMER  · MOVEMENT_SPECIAL_SUPPLIER
 *
 * Widens `context` (the new names are longer than 20 chars) and
 * re-creates the CHECK with the new values. No rows are seeded — ops
 * add the templates in Settings; until then the tabs fall back to the
 * built-in message.
 */
export class CommunicationTemplatesActivitySpecialContexts1789300000000 implements MigrationInterface {
  name = 'CommunicationTemplatesActivitySpecialContexts1789300000000';

  private async dropContextCheck(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 $$;
    `);
  }

  public async up(qr: QueryRunner): Promise<void> {
    await this.dropContextCheck(qr);
    await qr.query(`ALTER TABLE communication_templates ALTER COLUMN context TYPE varchar(40)`);
    await qr.query(
      `ALTER TABLE communication_templates
         ADD CONSTRAINT communication_templates_context_chk
           CHECK (context IN ('QUERY','BOOKING','MOVEMENT_CUSTOMER','MOVEMENT_SUPPLIER',
                              'MOVEMENT_ACTIVITY_CUSTOMER','MOVEMENT_ACTIVITY_SUPPLIER',
                              'MOVEMENT_SPECIAL_CUSTOMER','MOVEMENT_SPECIAL_SUPPLIER'))`,
    );
  }

  public async down(qr: QueryRunner): Promise<void> {
    await this.dropContextCheck(qr);
    await qr.query(
      `UPDATE communication_templates
          SET is_deleted = true
        WHERE context IN ('MOVEMENT_ACTIVITY_CUSTOMER','MOVEMENT_ACTIVITY_SUPPLIER',
                          'MOVEMENT_SPECIAL_CUSTOMER','MOVEMENT_SPECIAL_SUPPLIER')`,
    );
    await qr.query(
      `ALTER TABLE communication_templates
         ADD CONSTRAINT communication_templates_context_chk
           CHECK (context IN ('QUERY','BOOKING','MOVEMENT_CUSTOMER','MOVEMENT_SUPPLIER',
                              'MOVEMENT_ACTIVITY_CUSTOMER','MOVEMENT_ACTIVITY_SUPPLIER',
                              'MOVEMENT_SPECIAL_CUSTOMER','MOVEMENT_SPECIAL_SUPPLIER')
                  OR is_deleted = true)`,
    );
  }
}
