import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, IsNull } from 'typeorm';
import { ClsService } from 'nestjs-cls';
import { TenantAwareRepository } from '../../../common/repositories/tenant-aware.repository';
import { ServicePaymentCollectionConfirmationEntity } from '../../../entities/service-payment-collection-confirmation.entity';

/**
 * TenantAware repository for confirmation events.
 *
 * The hot-path query is "latest live confirmation for collection X" —
 * hit whenever MD renders the row. Backed by the partial
 * `ix_spcc_collection_live` index on the entity.
 */
@Injectable()
export class ServicePaymentCollectionConfirmationRepository extends TenantAwareRepository<ServicePaymentCollectionConfirmationEntity> {
  constructor(
    @InjectRepository(ServicePaymentCollectionConfirmationEntity)
    repo: Repository<ServicePaymentCollectionConfirmationEntity>,
    cls: ClsService,
  ) {
    super(repo, cls);
  }

  /** Latest LIVE (non-voided, non-deleted) confirmation for a
   *  collection. There's at most one at any time — a fresh confirm
   *  requires the caller to void the current live one first. */
  async findLatestLive(
    collectionId: string,
  ): Promise<ServicePaymentCollectionConfirmationEntity | null> {
    return this.findOne({
      where: {
        collection_id: collectionId,
        voided_at: IsNull(),
        is_deleted: false,
      } as any,
      relations: { collected_by_user: true },
      order: { collected_at: 'DESC' },
    });
  }

  /** Full history for a collection — live + voided, newest first.
   *  Powers the "history" strip on the confirmed row. */
  async findAllForCollection(
    collectionId: string,
  ): Promise<ServicePaymentCollectionConfirmationEntity[]> {
    return this.find({
      where: { collection_id: collectionId, is_deleted: false } as any,
      relations: { collected_by_user: true },
      order: { created_at: 'DESC' },
    });
  }
}
