<?php

namespace App\Insurance\Repository;

use App\Insurance\Entity\TenantInsurance;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

    /** @return TenantInsurance[] */
    public function findActiveByTenant(string $entityType, int $entityId): array
    {
        return $this->createQueryBuilder('t')
            ->where('t.entityType = :type')
            ->andWhere('t.entityId = :id')
            ->andWhere('t.isActive = true')
            ->setParameter('type', $entityType)
            ->setParameter('id', $entityId)
            ->orderBy('t.insuranceId', 'ASC')
            ->getQuery()
            ->getResult();
    }

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

    public function findActiveContract(string $entityType, int $entityId, int $insuranceId): ?TenantInsurance
    {
        return $this->createQueryBuilder('t')
            ->where('t.entityType = :type')
            ->andWhere('t.entityId = :id')
            ->andWhere('t.insuranceId = :ins')
            ->andWhere('t.isActive = true')
            ->setParameter('type', $entityType)
            ->setParameter('id', $entityId)
            ->setParameter('ins', $insuranceId)
            ->orderBy('t.version', 'DESC')
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }

    public function latestVersion(string $entityType, int $entityId, int $insuranceId): int
    {
        $max = $this->createQueryBuilder('t')
            ->select('MAX(t.version)')
            ->where('t.entityType = :type')
            ->andWhere('t.entityId = :id')
            ->andWhere('t.insuranceId = :ins')
            ->setParameter('type', $entityType)
            ->setParameter('id', $entityId)
            ->setParameter('ins', $insuranceId)
            ->getQuery()
            ->getSingleScalarResult();

        return (int) ($max ?? 0);
    }

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