import { MigrationInterface, QueryRunner } from "typeorm";

/**
 * Repair: AddEmailToOtpVerifications1900000000000 originally altered
 * `public.otp_verifications`, but the OtpVerification entity pins
 * schema: "freight". On any DB where that migration already ran (and is recorded
 * as executed, so it won't run again), the real `freight.otp_verifications` table
 * never got the `email` column and `phone` was never made nullable — so OTP send
 * dies with `column OtpVerification.email does not exist`.
 *
 * This migration re-applies the change against the correct schema. Idempotent
 * (IF NOT EXISTS / no-op DROP NOT NULL), and guarded so it's a no-op when the
 * freight table is absent.
 */
export class RepairOtpEmailSchema2020000000000 implements MigrationInterface {
  name = "RepairOtpEmailSchema2020000000000";

  public async up(queryRunner: QueryRunner): Promise<void> {
    const exists = await queryRunner.hasTable("freight.otp_verifications");
    if (!exists) return;

    await queryRunner.query(`
      ALTER TABLE freight.otp_verifications
      ALTER COLUMN phone DROP NOT NULL
    `);
    await queryRunner.query(`
      ALTER TABLE freight.otp_verifications
      ADD COLUMN IF NOT EXISTS email varchar UNIQUE
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    const exists = await queryRunner.hasTable("freight.otp_verifications");
    if (!exists) return;

    await queryRunner.query(`
      ALTER TABLE freight.otp_verifications
      DROP COLUMN IF EXISTS email
    `);
  }
}
