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 { PaymentCollectionEntity } from '../../../entities/payment-collection.entity';

/**
 * Append-only ledger of customer collection events. One row per
 * Payment Collection screen submission; child settlement_payments
 * rows reference it via `collection_id`.
 *
 * Mutations go through PaymentSettlementService so the cross-table
 * invariants (allocated_amount = SUM(child.paid_amount), receipt
 * sharing, booking/master rollups) stay consistent. This repo just
 * carries reads + the initial save.
 */
@Injectable()
export class PaymentCollectionRepository extends TenantAwareRepository<PaymentCollectionEntity> {
  constructor(
    @InjectRepository(PaymentCollectionEntity)
    repo: Repository<PaymentCollectionEntity>,
    cls: ClsService,
  ) {
    super(repo, cls);
  }

  async findByReceiptNo(receiptNo: string): Promise<PaymentCollectionEntity | null> {
    return this.findOne({
      where: { receipt_no: receiptNo } as any,
    });
  }
}
