<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\DI\Validation;

use PpPhp\Core\Platform\DI\Graph\DependencyGraphBuilder;
use PpPhp\Core\Platform\DI\Repository\DefinitionRepository;

final class ContainerValidator
{
    public function __construct(
        private readonly DependencyGraphBuilder $graphBuilder = new DependencyGraphBuilder(),
        private readonly CircularDependencyDetector $circular = new CircularDependencyDetector(),
        private readonly MissingDependencyDetector $missing = new MissingDependencyDetector()
    ) {}

    public function validate(DefinitionRepository $repository): ValidationResult
    {
        $result = new ValidationResult();
        $graph = $this->graphBuilder->build($repository);

        foreach ($this->circular->detect($graph) as $cycle) {
            $result->add(new ValidationIssue(
                'error',
                'Circular dependency detected: ' . implode(' -> ', $cycle),
                $cycle[0] ?? '',
                ['cycle' => $cycle]
            ));
        }

        foreach ($this->missing->detect($graph, $repository) as $missing) {
            $result->add(new ValidationIssue(
                'error',
                'Missing dependency: ' . $missing['to'],
                $missing['from'],
                $missing
            ));
        }

        return $result;
    }
}
