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

use InPost\International\Country;
use PrestaShop\PrestaShop\Core\Grid\Data\Factory\GridDataFactoryInterface;
use PrestaShop\PrestaShop\Core\Grid\Data\GridData;
use PrestaShop\PrestaShop\Core\Grid\Data\GridDataInterface;
use PrestaShop\PrestaShop\Core\Grid\Record\RecordCollection;
use PrestaShop\PrestaShop\Core\Grid\Search\SearchCriteriaInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

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

final class PickupAddressGridDataFactory implements GridDataFactoryInterface
{
    /**
     * @var GridDataFactoryInterface
     */
    private $dataFactory;

    /**
     * @var TranslatorInterface
     */
    private $translator;

    public function __construct(GridDataFactoryInterface $dataFactory, TranslatorInterface $translator)
    {
        $this->dataFactory = $dataFactory;
        $this->translator = $translator;
    }

    public function getData(SearchCriteriaInterface $searchCriteria): GridDataInterface
    {
        $data = $this->dataFactory->getData($searchCriteria);

        $records = array_map([$this, 'modifyRecord'], $data->getRecords()->all());

        return new GridData(
            new RecordCollection($records),
            $data->getRecordsTotal(),
            $data->getQuery()
        );
    }

    private function modifyRecord(array $record): array
    {
        $record['country'] = Country::from($record['country'])->trans($this->translator);

        return $record;
    }
}
