<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\ParcelTemplate;

use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use InPost\International\Entity\ParcelTemplate;

if (!defined('_PS_VERSION_')) {
    exit;
}

/**
 * @extends ServiceEntityRepository<ParcelTemplate>
 */
final class ParcelTemplateRepository extends ServiceEntityRepository implements ParcelTemplateRepositoryInterface
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, ParcelTemplate::class);
    }

    public function add(ParcelTemplate $template, bool $flush = true): void
    {
        $entityManager = $this->getEntityManager();
        $entityManager->persist($template);
        if ($flush) {
            $entityManager->flush();
        }
    }

    public function remove(ParcelTemplate $template, bool $flush = true): void
    {
        $entityManager = $this->getEntityManager();
        $entityManager->remove($template);
        if ($flush) {
            $entityManager->flush();
        }
    }

    public function getDefault(): ?ParcelTemplate
    {
        return $this->createQueryBuilder('t')
            ->andWhere('t.default = 1')
            ->getQuery()
            ->setMaxResults(1)
            ->getOneOrNullResult();
    }
}
