import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ClsService } from 'nestjs-cls';
import { TenantAwareRepository } from '../../../common/repositories/tenant-aware.repository';
import { CustomerInvoiceEntity } from '../../../entities/customer-invoice.entity';

/**
 * Tenant-aware repository for customer tax invoices. Writes flow
 * through AccountingService.generateCustomerInvoice — this repo
 * only carries lookups (latest non-void invoice for a booking, all
 * invoices for a booking).
 */
@Injectable()
export class CustomerInvoiceRepository extends TenantAwareRepository<CustomerInvoiceEntity> {
  constructor(
    @InjectRepository(CustomerInvoiceEntity)
    repo: Repository<CustomerInvoiceEntity>,
    cls: ClsService,
  ) {
    super(repo, cls);
  }

  async findForBooking(bookingId: string): Promise<CustomerInvoiceEntity[]> {
    return this.find({
      where: { booking_id: bookingId, is_deleted: false } as any,
      order: { invoice_date: 'DESC', created_at: 'DESC' } as any,
    });
  }

  async findLatestForBooking(bookingId: string): Promise<CustomerInvoiceEntity | null> {
    return this.findOne({
      where: { booking_id: bookingId, is_deleted: false, is_void: false } as any,
      order: { invoice_date: 'DESC', created_at: 'DESC' } as any,
    });
  }
}
