<?php

declare(strict_types=1);

namespace apexl\Io\modules\system\services;

use apexl\Io\exceptions\RecordNotFoundException;
use apexl\Io\interfaces\IoModuleInterface;
use function apexl\Io\assertInstanceOf;

final readonly class ModuleClassResolver
{

    /**
     * @return class-string<IoModuleInterface>
     * @throws RecordNotFoundException
     */
    public function resolve(string $candidate): string
    {
        if (str_contains($candidate, '\\')) {
            if (class_exists($candidate)) {
                assertInstanceOf($candidate, IoModuleInterface::class);

                return $candidate;
            }

            throw new RecordNotFoundException(sprintf('Tried `%s`', $candidate));
        }

        $class = sprintf('apexl\Io\modules\%1$s\%1$sModule', $candidate);

        if (class_exists($class)) {
            assertInstanceOf($class, IoModuleInterface::class);

            return $class;
        }

        throw new RecordNotFoundException(sprintf('Tried `%s`', $class));
    }
}