import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { InsuranceClaim, ClaimStatus } from '../../domain/entities/insurance-claim.entity';
import { IInsuranceClaimRepository } from '../../domain/repositories/insurance-claim.repository.interface';

@Injectable()
export class InsuranceClaimRepository implements IInsuranceClaimRepository {
  constructor(
    @InjectRepository(InsuranceClaim)
    private readonly repo: Repository<InsuranceClaim>,
  ) {}

  create(data: Partial<InsuranceClaim>): InsuranceClaim {
    return this.repo.create(data);
  }

  async save(claim: InsuranceClaim): Promise<InsuranceClaim> {
    return this.repo.save(claim);
  }

  async findById(id: string): Promise<InsuranceClaim | null> {
    return this.repo.findOne({ where: { id } });
  }

  async count(options?: { where?: Record<string, any> }): Promise<number> {
    return this.repo.count(options);
  }

  async findPaginated(
    page: number,
    limit: number,
    filters?: { status?: string },
  ): Promise<[InsuranceClaim[], number]> {
    const qb = this.repo.createQueryBuilder('claim');

    if (filters?.status) {
      qb.andWhere('claim.status = :status', { status: filters.status });
    }

    qb.orderBy('claim.created_at', 'DESC')
      .skip((page - 1) * limit)
      .take(limit);

    return qb.getManyAndCount();
  }

  async sumAmountByStatus(status: ClaimStatus): Promise<string> {
    const result = await this.repo
      .createQueryBuilder('claim')
      .select('COALESCE(SUM(claim.amount), 0)', 'total')
      .where('claim.status = :status', { status })
      .getRawOne();
    return result?.total || '0';
  }
}
