<?php

declare(strict_types=1);

namespace App\Module\ProjectManagement\Infrastructure\EventListener;

use App\Module\ProjectManagement\Domain\Entity\Project;
use App\Module\ProjectManagement\Domain\Repository\WorkflowRepositoryInterface;
use Doctrine\ORM\Event\PrePersistEventArgs;
use RuntimeException;

/**
 * Assigns the default workflow to a project when none was provided.
 * Guarantees the NOT NULL workflow_id constraint across every persistence
 * path (API Platform, raw API, MCP) without forcing the caller to supply one.
 */
final readonly class ProjectDefaultWorkflowListener
{
    public function __construct(private WorkflowRepositoryInterface $workflowRepository) {}

    public function prePersist(Project $project, PrePersistEventArgs $args): void
    {
        if (null !== $project->getWorkflow()) {
            return;
        }

        $default = $this->workflowRepository->findDefault()
            ?? ($this->workflowRepository->findBy([], ['position' => 'ASC'], 1)[0] ?? null);

        if (null === $default) {
            throw new RuntimeException('Cannot create a project: no workflow exists. Seed at least one workflow first.');
        }

        $project->setWorkflow($default);
    }
}
