<?php

declare(strict_types=1);


namespace apexl\Io\modules\mirror\Helper;

use apexl\Config\ConfigurationInterface;
use apexl\Config\Exceptions\MissingConfigException;
use apexl\Io\modules\mirror\Exception\UploaderException;
use apexl\Io\modules\mirror\Factory\UploaderServiceFactory;
use apexl\Io\modules\mirror\Interface\MirrorsFilesInterface;
use apexl\Io\modules\mirror\Interface\UploaderServiceInterface;
use DI\DependencyException;
use DI\NotFoundException;

final readonly class UploaderServiceResolver
{
    public function __construct(private ConfigurationInterface $config, private UploaderServiceFactory $uploaderFactory) {}

    /**
     * @throws DependencyException
     * @throws NotFoundException
     * @throws UploaderException
     */
    public function resolve(string $entityClass): ?UploaderServiceInterface
    {
        if (is_subclass_of($entityClass, MirrorsFilesInterface::class)) {
            return $entityClass::getUploader();
        }

        try {
            $class = $this->config->get('mirror.default_uploader');


            if ($class) {
                return $this->uploaderFactory->make($class);
            }

            $this->noDefaultUploader();
        } catch (MissingConfigException $e) {
            throw new UploaderException(message: $e->getMessage(), code: $e->getCode(), previous: $e);

        }

        return null;
    }

    /**
     * @throws MissingConfigException
     * @throws UploaderException
     */
    private function noDefaultUploader(): void
    {
        if (!$this->config->get('mirror.allow_no_default_uploader')) {
            throw new UploaderException(message: 'No default uploader has been specified in the configuration.');
        }
    }
}
