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

import { CustomerTruckAssignment } from './entities/customer-truck-assignment.entity';

@Injectable()
export class CustomerTruckAssignmentsRepository extends BaseRepository<CustomerTruckAssignment> {
  constructor(
    @InjectRepository(CustomerTruckAssignment)
    private readonly repo: Repository<CustomerTruckAssignment>,
  ) {
    super(repo);
  }

  /** All trucks assigned to a booking, oldest first, with their containers. */
  findByBookingId(bookingId: string): Promise<CustomerTruckAssignment[]> {
    return this.repo.find({
      where: { bookingId },
      relations: { containers: true },
      order: { assignedAt: 'ASC' },
    });
  }

  findByIdWithContainers(id: string): Promise<CustomerTruckAssignment | null> {
    return this.repo.findOne({ where: { id }, relations: { containers: true } });
  }
}
