import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Link each physical wagon move back to the transfer request that drove it, so
 * the history can show "Request S→K, 3× NX70 → wagons W101, W102, W103".
 * Nullable — legacy moves and non-request manual corrections carry no request.
 * Also indexes `moved_by_user_id` for the per-user history queries.
 */
export class LinkWagonMovementToTransferRequest2180000000000
  implements MigrationInterface
{
  name = 'LinkWagonMovementToTransferRequest2180000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.wagon_movements
        ADD COLUMN IF NOT EXISTS transfer_request_id uuid NULL
    `);
    await queryRunner.query(`
      DO $$
      BEGIN
        IF NOT EXISTS (
          SELECT 1 FROM pg_constraint WHERE conname = 'fk_wm_transfer_request'
        ) THEN
          ALTER TABLE freight.wagon_movements
            ADD CONSTRAINT fk_wm_transfer_request
            FOREIGN KEY (transfer_request_id)
            REFERENCES freight.wagon_transfer_requests (id) ON DELETE SET NULL;
        END IF;
      END $$;
    `);
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS idx_wm_transfer_request
        ON freight.wagon_movements (transfer_request_id)
    `);
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS idx_wm_moved_by
        ON freight.wagon_movements (moved_by_user_id)
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP INDEX IF EXISTS freight.idx_wm_moved_by`);
    await queryRunner.query(`DROP INDEX IF EXISTS freight.idx_wm_transfer_request`);
    await queryRunner.query(`
      ALTER TABLE freight.wagon_movements
        DROP CONSTRAINT IF EXISTS fk_wm_transfer_request
    `);
    await queryRunner.query(`
      ALTER TABLE freight.wagon_movements
        DROP COLUMN IF EXISTS transfer_request_id
    `);
  }
}
