<?php

namespace App\Insurance\Repository;

use App\Insurance\Entity\TenantServiceCategorySetting;
use App\Insurance\Enum\ServiceCategory;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

    /** @return array<string, bool> service_category => enabled, only stored rows */
    public function enabledMapFor(string $entityType, int $entityId): array
    {
        $rows = $this->findBy(['entityType' => $entityType, 'entityId' => $entityId]);

        $map = [];
        foreach ($rows as $row) {
            $map[$row->getServiceCategory()->value] = $row->isEnabled();
        }

        return $map;
    }

    public function findOneFor(string $entityType, int $entityId, ServiceCategory $category): ?TenantServiceCategorySetting
    {
        return $this->findOneBy([
            'entityType'      => $entityType,
            'entityId'        => $entityId,
            'serviceCategory' => $category,
        ]);
    }

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

    public function flush(): void
    {
        $this->getEntityManager()->flush();
    }
}
