<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\DI\Compiler\Factory;

use PpPhp\Core\Platform\DI\Definition\ClassDefinition;

final class FactoryGenerator
{
    public function __construct(
        private readonly FactoryCodeGenerator $code = new FactoryCodeGenerator(),
        private readonly CompiledFactoryWriter $writer = new CompiledFactoryWriter()
    ) {}

    public function generate(ClassDefinition $definition, string $basePath): FactoryGenerationResult
    {
        $namespace = 'PpPhp\\Storage\\Cache\\DI\\Factories';
        $shortClassName = FactoryClassName::fromServiceId($definition->id());
        $file = FactoryCachePaths::file($basePath, $shortClassName);

        try {
            $this->writer->write($file, $this->code->generate($definition, $namespace, $shortClassName));
            return new FactoryGenerationResult($definition->id(), $namespace . '\\' . $shortClassName, $file, true);
        } catch (\Throwable $e) {
            return new FactoryGenerationResult($definition->id(), $namespace . '\\' . $shortClassName, $file, false, [$e->getMessage()]);
        }
    }
}
