<?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\PickupAddress;

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

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

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

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

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

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