<?php

namespace App\Billing\Repository;

use App\Billing\Entity\Claim;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

class ClaimRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Claim::class);
    }

    public function findByUuid(string $uuid): ?Claim
    {
        return $this->findOneBy(['uuid' => $uuid]);
    }

    /** @return Claim[] */
    public function findByTenant(string $entityType, int $entityId, ?string $status = null): array
    {
        $qb = $this->createQueryBuilder('c')
            ->where('c.entityType = :type')
            ->andWhere('c.entityId = :id')
            ->setParameter('type', $entityType)
            ->setParameter('id', $entityId)
            ->orderBy('c.id', 'DESC');

        if ($status !== null) {
            $qb->andWhere('c.status = :status')->setParameter('status', $status);
        }

        return $qb->getQuery()->getResult();
    }

    /**
     * گزارش بدهی بیمه: جمع claimed/approved/paid بر اساس بیمه برای tenant.
     * @return array<int, array{insurance_id:int, claimed:int, approved:int, paid:int, debt:int}>
     */
    public function debtReport(string $entityType, int $entityId): array
    {
        $rows = $this->createQueryBuilder('c')
            ->select('c.insuranceId AS insurance_id')
            ->addSelect('SUM(c.totalClaimedRials) AS claimed')
            ->addSelect('SUM(COALESCE(c.totalApprovedRials, 0)) AS approved')
            ->addSelect('SUM(COALESCE(c.totalPaidRials, 0)) AS paid')
            ->where('c.entityType = :type')
            ->andWhere('c.entityId = :id')
            ->setParameter('type', $entityType)
            ->setParameter('id', $entityId)
            ->groupBy('c.insuranceId')
            ->getQuery()
            ->getArrayResult();

        return array_map(function (array $r) {
            $claimed  = (int) $r['claimed'];
            $paid     = (int) $r['paid'];
            return [
                'insurance_id' => (int) $r['insurance_id'],
                'claimed'      => $claimed,
                'approved'     => (int) $r['approved'],
                'paid'         => $paid,
                'debt'         => max(0, $claimed - $paid),
            ];
        }, $rows);
    }

    public function save(Claim $entity, bool $flush = true): void
    {
        $this->getEntityManager()->persist($entity);
        if ($flush) {
            $this->getEntityManager()->flush();
        }
    }
}
