import { Injectable, Logger } from '@nestjs/common';
import { DataSource } from 'typeorm';

import { Booking } from '../modules/bookings/entities/booking.entity';
import { TrainSchedule } from '../modules/train-schedules/entities/train-schedule.entity';
import { TrainScheduleBooking } from '../modules/train-schedules/entities/train-schedule-booking.entity';

/**
 * Makes the Batch 7 seed import train demonstrable for Batch 8: a booking riding an ARRIVED
 * train is IN_TRANSIT until unloaded, so flip the seed import train's assigned bookings to
 * IN_TRANSIT (an unload-eligible status). Idempotent — re-applying IN_TRANSIT is a no-op.
 */
@Injectable()
export class Batch8TestDataSeeder {
  private readonly logger = new Logger(Batch8TestDataSeeder.name);

  constructor(private readonly dataSource: DataSource) {}

  async run(): Promise<void> {
    try {
      const scheduleRepo = this.dataSource.getRepository(TrainSchedule);
      const scheduleBookingRepo = this.dataSource.getRepository(TrainScheduleBooking);
      const bookingRepo = this.dataSource.getRepository(Booking);

      const train = await scheduleRepo.findOne({ where: { trainNumber: 'SEED-IMP-TRAIN-01' } });
      if (!train) {
        this.logger.log('SEED-IMP-TRAIN-01 not found; skipping Batch 8 seed');
        return;
      }

      const links = await scheduleBookingRepo.find({ where: { trainScheduleId: train.id } });
      let updated = 0;
      for (const link of links) {
        const booking = await bookingRepo.findOne({ where: { id: link.bookingId } });
        if (!booking || booking.status === 'IN_TRANSIT') continue;
        await bookingRepo.update(booking.id, { status: 'IN_TRANSIT' });
        updated += 1;
      }

      if (updated > 0) {
        this.logger.log(`✅ Batch 8: set ${updated} import train booking(s) to IN_TRANSIT (unload-eligible)`);
      } else {
        this.logger.log('Batch 8: import train bookings already IN_TRANSIT, skipping');
      }
    } catch (error) {
      this.logger.error(
        `Batch8TestDataSeeder failed: ${error instanceof Error ? error.message : String(error)}`,
      );
    }
  }
}
