import { MigrationInterface, QueryRunner } from "typeorm";

/**
 * Repair migration. `SeparateVehicleAvailability1890000000000` is recorded in
 * public.migrations but the `availability` column is absent on some databases
 * (recorded-but-not-applied drift). Because the original is already recorded,
 * TypeORM will not re-run it, so `vehiclesService.findAll` (a query builder that
 * selects every entity column) 500s with `column "availability" does not exist`.
 *
 * This re-adds the column idempotently and backfills. Safe to run everywhere:
 * `IF NOT EXISTS` makes it a no-op where the column already exists.
 */
export class RepairVehicleAvailabilityColumn2110000000000
  implements MigrationInterface
{
  name = "RepairVehicleAvailabilityColumn2110000000000";

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.vehicles
      ADD COLUMN IF NOT EXISTS availability varchar DEFAULT 'FREE'
    `);
    await queryRunner.query(`
      UPDATE freight.vehicles SET availability = 'FREE' WHERE availability IS NULL
    `);
  }

  public async down(): Promise<void> {
    // No-op: dropping a column other code now depends on would reintroduce the
    // drift. The original SeparateVehicleAvailability migration owns the column.
  }
}
