import { MigrationInterface, QueryRunner } from "typeorm";

/**
 * Split the mixed vehicle status into two fields:
 * - status: operational state (ACTIVE, MAINTENANCE, RETIRED, OUT_OF_SERVICE)
 * - availability: assignment state (FREE, BUSY)
 *
 * Existing FREE/BUSY statuses are moved to availability and the status is
 * normalized back to ACTIVE.
 */
export class SeparateVehicleAvailability1890000000000 implements MigrationInterface {
  name = "SeparateVehicleAvailability1890000000000";

  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 = 'BUSY' WHERE status = 'BUSY'
    `);
    await queryRunner.query(`
      UPDATE freight.vehicles SET availability = 'FREE' WHERE availability IS NULL
    `);
    await queryRunner.query(`
      UPDATE freight.vehicles SET status = 'ACTIVE' WHERE status IN ('FREE', 'BUSY')
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // Fold availability back into status before dropping the column
    await queryRunner.query(`
      UPDATE freight.vehicles SET status = availability
      WHERE status = 'ACTIVE' AND availability IN ('FREE', 'BUSY')
    `);
    await queryRunner.query(`
      ALTER TABLE freight.vehicles DROP COLUMN IF EXISTS availability
    `);
  }
}
