<?php

declare(strict_types=1);

namespace App\Framework\View\Loading\Resolvers;

use App\Framework\Discovery\Results\DiscoveryRegistry;
use App\Framework\Filesystem\ValueObjects\FilePath;
use App\Framework\Filesystem\FileSystemService;

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

    public function __construct(
        private FileSystemService $fileSystem,
        private DiscoveryRegistry|null $discoverySource = null,
    ) {
    }

    public function resolve(string $template, ?string $controllerClass = null): ?string
    {
        if ($this->discoverySource === null) {
            return null;
        }

        return $this->resolveFromDiscoveryRegistry($template, $controllerClass);
    }

    private function resolveFromDiscoveryRegistry(string $template, ?string $controllerClass): ?string
    {
        // Strategie 1: Direkter Template-Name-Match
        $templateMapping = $this->discoverySource->templates->get($template);
        if ($templateMapping) {
            return $this->validateTemplatePath($templateMapping->path);
        }

        // Strategie 2: Template mit Extension
        $templateWithExt = $template . self::TEMPLATE_EXTENSION;
        $templateMapping = $this->discoverySource->templates->get($templateWithExt);
        if ($templateMapping) {
            return $this->validateTemplatePath($templateMapping->path);
        }

        // Strategie 3: Suche in allen Templates
        foreach ($this->discoverySource->templates->getAll() as $templateMapping) {
            if ($this->templateMatches($templateMapping->name, $template)) {
                return $this->validateTemplatePath($templateMapping->path);
            }
        }

        return null;
    }

    private function validateTemplatePath(FilePath $path): ?string
    {
        return $this->fileSystem->fileExists($path) ? $path->toString() : null;
        #return file_exists($path) ? $path : null;
    }

    private function templateMatches(string $templateName, string $searchTemplate): bool
    {
        // Entferne Extension für Vergleich (.view.php oder nur .view)
        $cleanTemplateName = str_replace(self::TEMPLATE_EXTENSION, '', $templateName);
        $cleanTemplateName = str_replace('.view', '', $cleanTemplateName);

        return $cleanTemplateName === $searchTemplate ||
               basename($cleanTemplateName) === $searchTemplate;
    }
}
