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

/**
 * Append-only ledger of payments against a payment_settlements row.
 *
 * Existence-only methods here — the running total per parent settlement
 * is kept on the parent's `amount_settled` column (maintained by
 * PaymentSettlementService.recordPayment) so the list page doesn't
 * have to sum the ledger on every read.
 */
@Injectable()
export class SettlementPaymentRepository extends TenantAwareRepository<SettlementPaymentEntity> {
  constructor(
    @InjectRepository(SettlementPaymentEntity)
    repo: Repository<SettlementPaymentEntity>,
    cls: ClsService,
  ) {
    super(repo, cls);
  }

  /**
   * Full ledger for one settlement, oldest-first. Powers the
   * "Payment History" table on the settlement detail page.
   */
  async findBySettlement(settlementId: string): Promise<SettlementPaymentEntity[]> {
    return this.find({
      where: { settlement_id: settlementId },
      order: { paid_date: 'ASC', created_at: 'ASC' },
    });
  }

  /** Live (non-void) payments for one Collect Payment event. */
  async findByCollection(collectionId: string): Promise<SettlementPaymentEntity[]> {
    return this.find({
      where: { collection_id: collectionId, is_void: false } as never,
      order: { created_at: 'ASC' },
    });
  }
}
