<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\ObjectModel;

final class Hydrator implements HydratorInterface
{
    /**
     * {@inheritdoc}
     *
     * @throws \PrestaShopException
     */
    public function hydrate(array $data, string $class, ?int $languageId = null): \ObjectModel
    {
        if (!is_int(key($data))) {
            $data = [$data];
        }

        $collection = $this->hydrateCollection($data, $class, $languageId);
        if (1 !== $count = count($collection)) {
            throw new \LogicException(sprintf('Unexpected collection count. Expected: 1, got: %d.', $count));
        }

        return current($collection);
    }

    /**
     * @template T of \ObjectModel
     *
     * @param class-string<T> $class
     *
     * @return T[]
     *
     * @throws \PrestaShopException
     */
    public function hydrateCollection(array $data, string $class, ?int $languageId = null): array
    {
        return $class::hydrateCollection($class, $data, $languageId);
    }
}
