<?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\Carrier\Grid;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\ParameterType;
use Doctrine\DBAL\Query\QueryBuilder;
use PrestaShop\PrestaShop\Adapter\Shop\Context;
use PrestaShop\PrestaShop\Core\Grid\Query\AbstractDoctrineQueryBuilder;
use PrestaShop\PrestaShop\Core\Grid\Query\DoctrineSearchCriteriaApplicatorInterface;
use PrestaShop\PrestaShop\Core\Grid\Search\SearchCriteriaInterface;

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

final class CarrierQueryBuilder extends AbstractDoctrineQueryBuilder
{
    /**
     * @var DoctrineSearchCriteriaApplicatorInterface
     */
    private $searchCriteriaApplicator;

    /**
     * @var Context
     */
    private $shopContext;

    public function __construct(Connection $connection, string $dbPrefix, DoctrineSearchCriteriaApplicatorInterface $searchCriteriaApplicator, Context $shopContext)
    {
        parent::__construct($connection, $dbPrefix);
        $this->searchCriteriaApplicator = $searchCriteriaApplicator;
        $this->shopContext = $shopContext;
    }

    public function getSearchQueryBuilder(SearchCriteriaInterface $searchCriteria): QueryBuilder
    {
        $queryBuilder = $this
            ->getCommonQueryBuilder($searchCriteria)
            ->select('i.*, c.name, c.id_carrier, c.active');

        $this->searchCriteriaApplicator
            ->applyPagination($searchCriteria, $queryBuilder)
            ->applySorting($searchCriteria, $queryBuilder);

        return $queryBuilder;
    }

    public function getCountQueryBuilder(SearchCriteriaInterface $searchCriteria): QueryBuilder
    {
        return $this
            ->getCommonQueryBuilder($searchCriteria)
            ->select('COUNT(*)');
    }

    private function getCommonQueryBuilder(SearchCriteriaInterface $searchCriteria): QueryBuilder
    {
        $qb = $this->connection
            ->createQueryBuilder()
            ->from($this->dbPrefix . 'inpost_intl_carrier', 'i')
            ->innerJoin('i', $this->dbPrefix . 'carrier', 'c', 'c.id_reference = i.id_reference AND c.deleted = 0');

        $this->applyFilters($searchCriteria->getFilters(), $qb);

        if ($this->shopContext->isAllShopContext()) {
            return $qb;
        }

        return $qb
            ->innerJoin('c', $this->dbPrefix . 'carrier_shop', 'cs', 'cs.id_carrier = c.id_carrier')
            ->andWhere('cs.id_shop IN (:shop_ids)')
            ->setParameter('shop_ids', $this->shopContext->getContextListShopID(), Connection::PARAM_INT_ARRAY);
    }

    /**
     * @param array<string, mixed> $filters
     */
    private function applyFilters(array $filters, QueryBuilder $qb): void
    {
        foreach ($filters as $filterName => $filterValue) {
            switch ($filterName) {
                case 'id_reference':
                case 'type':
                    $qb->andWhere('i.' . $filterName . ' = :' . $filterName);
                    $qb->setParameter($filterName, $filterValue);

                    break;
                case 'countries':
                    $qb->andWhere('i.countries LIKE :countries');
                    $qb->setParameter('countries', '%' . $filterValue . '%');

                    break;
                case 'name':
                    $qb->andWhere('c.name LIKE :name');
                    $qb->setParameter('name', '%' . $filterValue . '%');

                    break;
                case 'active':
                    $qb->andWhere('c.active LIKE :active');
                    $qb->setParameter('active', $filterValue, ParameterType::BOOLEAN);

                    break;
                default:
                    break;
            }
        }
    }
}
