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

/**
 * Add driver assignment fields to vehicles table
 */
export class AddVehicleDriverAssignment1800000000001 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    const vehiclesTable = await queryRunner.getTable('freight.vehicles');
    if (vehiclesTable) {
      const hasAssignedDriverId = vehiclesTable.columns.some((col) => col.name === 'assigned_driver_id');
      if (!hasAssignedDriverId) {
        await queryRunner.addColumn(
          'freight.vehicles',
          new TableColumn({
            name: 'assigned_driver_id',
            type: 'uuid',
            isNullable: true,
          }),
        );
      }

      const hasAssignedDriverName = vehiclesTable.columns.some((col) => col.name === 'assigned_driver_name');
      if (!hasAssignedDriverName) {
        await queryRunner.addColumn(
          'freight.vehicles',
          new TableColumn({
            name: 'assigned_driver_name',
            type: 'varchar',
            isNullable: true,
          }),
        );
      }
    }
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    const vehiclesTable = await queryRunner.getTable('freight.vehicles');
    if (vehiclesTable) {
      const hasAssignedDriverId = vehiclesTable.columns.some((col) => col.name === 'assigned_driver_id');
      if (hasAssignedDriverId) {
        await queryRunner.dropColumn('freight.vehicles', 'assigned_driver_id');
      }

      const hasAssignedDriverName = vehiclesTable.columns.some((col) => col.name === 'assigned_driver_name');
      if (hasAssignedDriverName) {
        await queryRunner.dropColumn('freight.vehicles', 'assigned_driver_name');
      }
    }
  }
}
