/**
 * Shipment Counter Repository
 *
 * Counts total shipments (bookings + CSV bookings) for an organization in a year.
 * Used to enforce Bronze plan's 12 shipments/year limit.
 */

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ShipmentCounterPort } from '@domain/ports/out/shipment-counter.port';
import { CsvBookingOrmEntity } from '../entities/csv-booking.orm-entity';

@Injectable()
export class TypeOrmShipmentCounterRepository implements ShipmentCounterPort {
  constructor(
    @InjectRepository(CsvBookingOrmEntity)
    private readonly csvBookingRepository: Repository<CsvBookingOrmEntity>
  ) {}

  async countShipmentsForOrganizationInYear(organizationId: string, year: number): Promise<number> {
    const startOfYear = new Date(year, 0, 1);
    const startOfNextYear = new Date(year + 1, 0, 1);

    return this.csvBookingRepository
      .createQueryBuilder('csv_booking')
      .where('csv_booking.organization_id = :organizationId', { organizationId })
      .andWhere('csv_booking.created_at >= :start', { start: startOfYear })
      .andWhere('csv_booking.created_at < :end', { end: startOfNextYear })
      .getCount();
  }
}
