import { MigrationInterface, QueryRunner } from 'typeorm';

export class AddCurrentLocationToWagons1750300000000 implements MigrationInterface {
  name = 'AddCurrentLocationToWagons1750300000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.wagons
      ADD COLUMN IF NOT EXISTS current_location_yard_id UUID NULL;
    `);

    await queryRunner.query(`
      DO $$
      BEGIN
        IF NOT EXISTS (
          SELECT 1
          FROM information_schema.table_constraints
          WHERE constraint_schema = 'freight'
            AND table_name = 'wagons'
            AND constraint_name = 'FK_wagons_current_location_yard_id'
        ) THEN
          ALTER TABLE freight.wagons
          ADD CONSTRAINT "FK_wagons_current_location_yard_id"
          FOREIGN KEY (current_location_yard_id)
          REFERENCES freight.yards(id)
          ON DELETE SET NULL;
        END IF;
      END $$;
    `);

    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS "IDX_wagons_current_location_yard_id"
      ON freight.wagons(current_location_yard_id);
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP INDEX IF EXISTS freight."IDX_wagons_current_location_yard_id";`);
    await queryRunner.query(`
      ALTER TABLE freight.wagons
      DROP CONSTRAINT IF EXISTS "FK_wagons_current_location_yard_id";
    `);
    await queryRunner.query(`
      ALTER TABLE freight.wagons
      DROP COLUMN IF EXISTS current_location_yard_id;
    `);
  }
}
