import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.train_set_wagons
      ADD COLUMN IF NOT EXISTS physical_wagon_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 = 'train_set_wagons'
            AND constraint_name = 'fk_train_set_wagons_physical_wagon'
        ) THEN
          ALTER TABLE freight.train_set_wagons
          ADD CONSTRAINT fk_train_set_wagons_physical_wagon
          FOREIGN KEY (physical_wagon_id)
          REFERENCES freight.wagons(id)
          ON DELETE SET NULL;
        END IF;
      END $$;
    `);

    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS idx_train_set_wagons_physical_wagon
      ON freight.train_set_wagons(physical_wagon_id);
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP INDEX IF EXISTS freight.idx_train_set_wagons_physical_wagon;`);
    await queryRunner.query(`
      ALTER TABLE freight.train_set_wagons
      DROP CONSTRAINT IF EXISTS fk_train_set_wagons_physical_wagon;
    `);
    await queryRunner.query(`
      ALTER TABLE freight.train_set_wagons
      DROP COLUMN IF EXISTS physical_wagon_id;
    `);
  }
}
