<?php

declare(strict_types=1);

namespace App\Framework\View\Loading\Resolvers;

final readonly class ControllerResolver implements TemplateResolverStrategy
{
    public const string TEMPLATE_EXTENSION = '.view.php';

    public function resolve(string $template, ?string $controllerClass = null): ?string
    {
        if (! $controllerClass) {
            return null;
        }

        try {
            $rc = new \ReflectionClass($controllerClass);
            $dir = dirname($rc->getFileName());

            // First try direct controller directory
            $path = $dir . DIRECTORY_SEPARATOR . $template . self::TEMPLATE_EXTENSION;
            if (file_exists($path)) {
                return $path;
            }

            // Then try templates subdirectory
            $templatesPath = $dir . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . $template . self::TEMPLATE_EXTENSION;
            if (file_exists($templatesPath)) {
                return $templatesPath;
            }

            return null;
        } catch (\ReflectionException) {
            return null;
        }
    }
}
