<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\ObjectModel\Repository;

use Doctrine\DBAL\Connection;
use Gls\GlsPoland\PrestaShop\ObjectModel\HydratorInterface;

/**
 * @extends AbstractObjectModelRepository<\Order>
 */
final class OrderRepository extends AbstractObjectModelRepository
{
    public function __construct(Connection $connection, string $dbPrefix, HydratorInterface $hydrator = null)
    {
        parent::__construct(\Order::class, $connection, $dbPrefix, $hydrator);
    }

    public function findByCarrierModuleName(string $moduleName, int ...$orderIds): array
    {
        $qb = $this
            ->createQueryBuilder('o')
            ->innerJoin('o', 'carrier', 'c', 'c.id_carrier = o.id_carrier')
            ->andWhere('c.external_module_name = :moduleName')
            ->setParameter('moduleName', $moduleName);

        if ([] !== $orderIds) {
            $qb
                ->andWhere('o.id_order IN (:orderIds)')
                ->setParameter('orderIds', $orderIds, Connection::PARAM_INT_ARRAY);
        }

        $statement = $qb->execute();
        $data = $this->fetchAllAssociative($statement);

        return $this->hydrateCollection($data);
    }
}
