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

export class AddFacilityIdToWarehouses1750000000001 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    const table = await queryRunner.getTable('freight.warehouses');
    if (!table) {
      // warehouses table doesn't exist yet, skip this migration
      return;
    }

    const hasColumn = table.columns.some((col) => col.name === 'facility_id');
    if (hasColumn) {
      // Column already exists, skip
      return;
    }

    await queryRunner.addColumn(
      'freight.warehouses',
      new TableColumn({
        name: 'facility_id',
        type: 'uuid',
        isNullable: true,
      }),
    );

    await queryRunner.createForeignKey(
      'freight.warehouses',
      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('freight.warehouses');
    if (!table) {
      return;
    }
    const foreignKey = table.foreignKeys.find((fk) => fk.columnNames.includes('facility_id'));
    if (foreignKey) {
      await queryRunner.dropForeignKey('freight.warehouses', foreignKey);
    }
    const hasColumn = table.columns.some((col) => col.name === 'facility_id');
    if (hasColumn) {
      await queryRunner.dropColumn('freight.warehouses', 'facility_id');
    }
  }
}
