import { MigrationInterface, QueryRunner } from "typeorm";

/**
 * Make driver uniqueness soft-delete aware. The original table used plain
 * column UNIQUE constraints (drivers_email_key, etc.) which count soft-deleted
 * rows, so deleting a driver then re-adding the same email/phone/license/Fayda
 * identity failed at the DB with a raw 500 — even though the service's own
 * (deleted_at-excluding) duplicate check saw nothing. Replace them with partial
 * unique indexes scoped to live rows (deleted_at IS NULL) so uniqueness matches
 * what the service enforces and freed values become reusable after deletion.
 */
export class DriverUniquePartialSoftDelete1890000000007 implements MigrationInterface {
  name = "DriverUniquePartialSoftDelete1890000000007";

  public async up(queryRunner: QueryRunner): Promise<void> {
    // Drop the full-table unique constraints from CreateDriversTable...
    await queryRunner.query(`
      ALTER TABLE freight.drivers
        DROP CONSTRAINT IF EXISTS drivers_email_key,
        DROP CONSTRAINT IF EXISTS drivers_phone_number_key,
        DROP CONSTRAINT IF EXISTS drivers_license_number_key
    `);
    // ...and the plain fayda_sub unique index from 1890000000006.
    await queryRunner.query(`DROP INDEX IF EXISTS freight."UQ_DRIVERS_FAYDA_SUB"`);

    // Re-add each as a partial unique index scoped to non-deleted rows.
    await queryRunner.query(`
      CREATE UNIQUE INDEX IF NOT EXISTS "UQ_DRIVERS_EMAIL_ACTIVE"
      ON freight.drivers (email) WHERE deleted_at IS NULL
    `);
    await queryRunner.query(`
      CREATE UNIQUE INDEX IF NOT EXISTS "UQ_DRIVERS_PHONE_ACTIVE"
      ON freight.drivers (phone_number) WHERE deleted_at IS NULL
    `);
    await queryRunner.query(`
      CREATE UNIQUE INDEX IF NOT EXISTS "UQ_DRIVERS_LICENSE_ACTIVE"
      ON freight.drivers (license_number) WHERE deleted_at IS NULL
    `);
    await queryRunner.query(`
      CREATE UNIQUE INDEX IF NOT EXISTS "UQ_DRIVERS_FAYDA_SUB_ACTIVE"
      ON freight.drivers (fayda_sub) WHERE deleted_at IS NULL
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP INDEX IF EXISTS freight."UQ_DRIVERS_EMAIL_ACTIVE"`);
    await queryRunner.query(`DROP INDEX IF EXISTS freight."UQ_DRIVERS_PHONE_ACTIVE"`);
    await queryRunner.query(`DROP INDEX IF EXISTS freight."UQ_DRIVERS_LICENSE_ACTIVE"`);
    await queryRunner.query(`DROP INDEX IF EXISTS freight."UQ_DRIVERS_FAYDA_SUB_ACTIVE"`);

    await queryRunner.query(`
      CREATE UNIQUE INDEX IF NOT EXISTS "UQ_DRIVERS_FAYDA_SUB"
      ON freight.drivers (fayda_sub)
    `);
    await queryRunner.query(`
      ALTER TABLE freight.drivers
        ADD CONSTRAINT drivers_email_key UNIQUE (email),
        ADD CONSTRAINT drivers_phone_number_key UNIQUE (phone_number),
        ADD CONSTRAINT drivers_license_number_key UNIQUE (license_number)
    `);
  }
}
