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

import { TrainScheduleBooking } from './entities/train-schedule-booking.entity';

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

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

  async createMany(
    records: DeepPartial<TrainScheduleBooking>[],
    manager?: EntityManager,
  ): Promise<TrainScheduleBooking[]> {
    if (!records.length) return [];
    const repo = this.repo(manager);
    return repo.save(repo.create(records));
  }

  async deleteByScheduleAndBooking(
    trainScheduleId: string,
    bookingId: string,
    manager?: EntityManager,
  ): Promise<void> {
    await this.repo(manager).delete({ trainScheduleId, bookingId });
  }

  async existsForBooking(bookingId: string, manager?: EntityManager): Promise<boolean> {
    const count = await this.repo(manager).count({ where: { bookingId } });
    return count > 0;
  }

  findByBookingIds(bookingIds: string[], manager?: EntityManager): Promise<TrainScheduleBooking[]> {
    if (!bookingIds.length) return Promise.resolve([]);
    return this.repo(manager).find({
      where: { bookingId: In(bookingIds) },
      select: { id: true, bookingId: true, trainScheduleId: true },
    });
  }
}
