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 {
  CustomerCreditLedgerEntity,
  CreditLedgerPartyType,
} from '../../../entities/customer-credit-ledger.entity';

/**
 * Phase D §12d — credit ledger header repo. Reads/writes go through
 * the service so balance + movement stay transactionally aligned;
 * this repo only carries lookup convenience.
 */
@Injectable()
export class CustomerCreditLedgerRepository extends TenantAwareRepository<CustomerCreditLedgerEntity> {
  constructor(
    @InjectRepository(CustomerCreditLedgerEntity)
    repo: Repository<CustomerCreditLedgerEntity>,
    cls: ClsService,
  ) {
    super(repo, cls);
  }

  async findByParty(
    partyType: CreditLedgerPartyType,
    partyKey: string,
    currencyId: string,
  ): Promise<CustomerCreditLedgerEntity | null> {
    return this.findOne({
      where: {
        party_type: partyType,
        party_key: partyKey,
        currency_id: currencyId,
        is_deleted: false,
      } as any,
    });
  }
}
