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

/**
 * `queries.guest_name` → NULL-able.
 *
 * Sibling to 1780300000000-QueryGuestMobileNullable. Same rationale:
 * the FE Zod schema already treats `guest_name` as optional (walk-in
 * and lead-stage queries land before guest identity is known), but
 * the BE DTO + DB column kept NOT NULL. Saves with a blank name were
 * 400-ing at the validation layer before the row was ever attempted.
 *
 * Existing rows are untouched.
 *
 * Down: restore NOT NULL only when no NULL rows exist.
 */
export class QueryGuestNameNullable1780400000000 implements MigrationInterface {
  async up(qr: QueryRunner): Promise<void> {
    await qr.query(`ALTER TABLE queries ALTER COLUMN guest_name DROP NOT NULL;`);
  }

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