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

use InPost\International\PrestaShop\ObjectModel\ObjectManagerInterface;
use Psr\Container\ContainerInterface;

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

final class ObjectRepositoryFactory implements ObjectRepositoryFactoryInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    private $repositories = [];

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function getRepository(ObjectManagerInterface $manager, string $class): ObjectRepositoryInterface
    {
        if ($this->container->has($class)) {
            return $this->container->get($class);
        }

        return $this->repositories[$class] ?? ($this->repositories[$class] = $this->createRepository($manager, $class));
    }

    private function createRepository(ObjectManagerInterface $manager, string $class): ObjectRepositoryInterface
    {
        return new ObjectRepository($class, $manager);
    }
}
