import { type MigrationInterface, type QueryRunner } from 'typeorm';

/**
 * `queries.guest_mobile` → NULL-able.
 *
 * The Zod schema on the FE has treated guest_mobile as optional for a
 * while (walk-ins, email-only leads), but the BE DTO + DB column kept
 * a NOT NULL. Saves with a blank mobile were 400-ing at the validation
 * layer before the row was ever attempted.
 *
 * This migration drops the NOT NULL on the column to match the relaxed
 * DTO (see `CreateQueryDto.guest_mobile`). Existing rows are untouched.
 *
 * Down: restore NOT NULL only when no NULLs exist (defensive — if any
 * walk-in queries landed in the meantime, the down would fail without
 * the guard).
 *
 * NOTE: `guest_name` is relaxed in a follow-up migration
 * (1780400000000-QueryGuestNameNullable). They're kept as separate
 * migrations because this one already ran on localhost before the
 * decision to also relax guest_name landed.
 */
export class QueryGuestMobileNullable1780300000000 implements MigrationInterface {
  async up(qr: QueryRunner): Promise<void> {
    await qr.query(`ALTER TABLE queries ALTER COLUMN guest_mobile DROP NOT NULL;`);
  }

  async down(qr: QueryRunner): Promise<void> {
    const rows = (await qr.query(
      `SELECT COUNT(*)::int AS c FROM queries WHERE guest_mobile IS NULL;`,
    )) as Array<{ c: number }>;
    if ((rows[0]?.c ?? 0) > 0) {
      throw new Error(
        'Cannot revert guest_mobile to NOT NULL — existing NULL rows present. ' +
          'Backfill phones first or drop the rows manually.',
      );
    }
    await qr.query(`ALTER TABLE queries ALTER COLUMN guest_mobile SET NOT NULL;`);
  }
}
