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

import { WagonAllocationContainerItem } from './entities/wagon-allocation-container-item.entity';

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

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

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

  async deleteByAllocationIds(allocationIds: string[], manager?: EntityManager): Promise<void> {
    if (!allocationIds.length) return;
    await this.repo(manager).delete({ wagonBookingAllocationId: In(allocationIds) });
  }
}
