import { BaseRepository } from '@edr/api-common';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { EntityManager, Repository } from 'typeorm';

import { TrainSchedule, TrainScheduleStatus } from './entities/train-schedule.entity';

@Injectable()
export class TrainSchedulesRepository extends BaseRepository<TrainSchedule> {
  constructor(
    @InjectRepository(TrainSchedule)
    repository: Repository<TrainSchedule>,
  ) {
    super(repository);
  }

  private repo(manager?: EntityManager) {
    return manager ? manager.getRepository(TrainSchedule) : this.repository;
  }

  findByIdWithFullGraph(id: string, manager?: EntityManager): Promise<TrainSchedule | null> {
    return this.repo(manager).findOne({
      where: { id },
      relations: {
        route: true,
        trainSet: {
          locomotive: true,
          wagons: {
            wagonType: true,
            physicalWagon: true,
            allocations: {
              booking: { company: true, bookingContainers: { containerType: true } },
              containerItems: true,
            },
          },
        },
        originStation: true,
        destinationStation: true,
        scheduleBookings: {
          booking: {
            company: true,
            originYard: true,
            destinationYard: true,
            bookingContainers: { containerType: true },
            cargoType: true,
          },
        },
      },
    });
  }

  async updateStatus(
    id: string,
    status: TrainScheduleStatus,
    extra?: Partial<TrainSchedule>,
    manager?: EntityManager,
  ): Promise<void> {
    await this.repo(manager).update(id, { status, ...extra } as never);
  }
}
