<?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\PrestaShop\ObjectModel\Form\DataTransformer;

use InPost\International\PrestaShop\ObjectModel\ObjectManagerInterface;
use InPost\International\PrestaShop\ObjectModel\OrderMaintainingLoaderTrait;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

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

/**
 * @template T of \ObjectModel
 */
final class ObjectModelCollectionToIdsTransformer implements DataTransformerInterface
{
    use OrderMaintainingLoaderTrait;

    /**
     * @var class-string<T>
     */
    private $class;

    /**
     * @var int|null
     */
    private $languageId;

    /**
     * @var int|null
     */
    private $shopId;

    /**
     * @param class-string<T> $class
     */
    public function __construct(ObjectManagerInterface $manager, string $class, int $languageId = null, int $shopId = null)
    {
        $this->shopId = $shopId;
        $this->languageId = $languageId;
        $this->class = $class;
        $this->manager = $manager;
    }

    /**
     * {@inheritDoc}
     */
    public function transform($value): ?array
    {
        if (null === $value) {
            return null;
        }

        if (!is_array($value)) {
            throw new TransformationFailedException('Expected an array.');
        }

        return array_map(function ($element): int {
            if (!$element instanceof $this->class) {
                throw new TransformationFailedException(sprintf('Expected an instance of "%s".', $this->class));
            }

            return (int) $element->id;
        }, $value);
    }

    /**
     * {@inheritDoc}
     *
     * @return T[]|null
     */
    public function reverseTransform($value): ?array
    {
        if (null === $value) {
            return null;
        }

        if (!is_array($value)) {
            throw new TransformationFailedException('Expected an array.');
        }

        return $this->findByIdsMaintainingOrder(
            $this->class,
            $value,
            $this->languageId,
            $this->shopId
        );
    }
}
