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

/**
 * Coerce existing drivers.license_no = '' to NULL.
 *
 * The unique partial index on (tenant_id, license_no) WHERE
 * is_deleted = false treats two empty strings as a duplicate. Postgres'
 * NULL-is-distinct rule means multiple NULLs are fine, but '' isn't.
 * DriverService.update used to spread the DTO raw, so a blank license
 * field on the form persisted as '' and blocked any subsequent driver
 * edit in the same tenant.
 *
 * The service-layer fix (commit 66d5dce) coerces '' → NULL on the way
 * in. This migration cleans up rows already saved with '' so the next
 * save on those tenants doesn't trip the index.
 *
 * Idempotent: re-running just updates 0 rows. Safe on every env.
 */
export class NormalizeEmptyDriverLicenses1777400000000 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`UPDATE "drivers" SET "license_no" = NULL WHERE "license_no" = ''`);
  }

  public async down(): Promise<void> {
    // No-op — we can't recover which rows were originally '' vs NULL.
    // Reversing would arbitrarily clobber valid NULL rows back to ''.
  }
}
