import { BaseRepository } from '@edr/api-common';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { BookingOrder } from './entities/booking-order.entity';

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

  /** Orders placed against a given contract, newest first, with their lines. */
  findByContract(contractBookingId: string): Promise<BookingOrder[]> {
    return this.repository.find({
      where: { contractBookingId },
      relations: { lines: { containerType: true }, booking: true },
      order: { createdAt: 'DESC' },
    });
  }

  override findById(id: string): Promise<BookingOrder | null> {
    return this.repository.findOne({
      where: { id },
      relations: { lines: { containerType: true }, booking: true, contractBooking: true },
    });
  }

  /** Count this calendar year's orders, for reference generation. */
  async countByYear(year: number): Promise<number> {
    const start = new Date(Date.UTC(year, 0, 1));
    const end = new Date(Date.UTC(year + 1, 0, 1));
    return this.repository
      .createQueryBuilder('o')
      .where('o.createdAt >= :start AND o.createdAt < :end', { start, end })
      .getCount();
  }
}
