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

/**
 * Fix: migration 1750000000001 (AddFacilityIdToWarehouses) silently skipped because
 * the freight.warehouses table didn't exist yet at that timestamp. The column was
 * never added. Add it now with idempotent guards.
 */
export class AddFacilityIdToWarehousesFix1791000000004 implements MigrationInterface {
  private readonly table = 'freight.warehouses';

  public async up(queryRunner: QueryRunner): Promise<void> {
    if (!(await queryRunner.hasColumn(this.table, 'facility_id'))) {
      await queryRunner.addColumn(
        this.table,
        new TableColumn({
          name: 'facility_id',
          type: 'uuid',
          isNullable: true,
        }),
      );
    }

    const table = await queryRunner.getTable(this.table);
    const hasFk = table?.foreignKeys.some((fk) => fk.columnNames.includes('facility_id'));
    if (!hasFk) {
      await queryRunner.createForeignKey(
        this.table,
        new TableForeignKey({
          columnNames: ['facility_id'],
          referencedColumnNames: ['id'],
          referencedTableName: 'facilities',
          referencedSchema: 'freight',
          onDelete: 'SET NULL',
        }),
      );
    }
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    const table = await queryRunner.getTable(this.table);
    if (!table) return;

    const foreignKey = table.foreignKeys.find((fk) => fk.columnNames.includes('facility_id'));
    if (foreignKey) {
      await queryRunner.dropForeignKey(this.table, foreignKey);
    }

    if (await queryRunner.hasColumn(this.table, 'facility_id')) {
      await queryRunner.dropColumn(this.table, 'facility_id');
    }
  }
}
