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

use InPost\International\Carrier\CarrierConfiguration;
use InPost\International\Carrier\Message\CreateCarrierCommand;
use InPost\International\PrestaShop\ObjectModel\Repository\ObjectRepositoryInterface;

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

final class GroupsConfigurator implements CarrierConfiguratorInterface
{
    /**
     * @var ObjectRepositoryInterface<\Group>
     */
    private $repository;

    /**
     * @var int[]|null
     */
    private $groupIds;

    /**
     * @param ObjectRepositoryInterface<\Group> $repository
     */
    public function __construct(ObjectRepositoryInterface $repository)
    {
        $this->repository = $repository;
    }

    public function configure(CarrierConfiguration $configuration, CreateCarrierCommand $command): void
    {
        foreach ($this->getGroupIds() as $groupId) {
            $configuration->addGroup($groupId);
        }
    }

    /**
     * @return int[]
     */
    private function getGroupIds(): array
    {
        return $this->groupIds = $this->groupIds ?? array_map(static function (\Group $group): int {
            return (int) $group->id;
        }, $this->repository->findAll());
    }
}
