<?php

declare(strict_types=1);

namespace App\Module\Integration\Infrastructure\ApiPlatform\State;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Module\Integration\Infrastructure\ApiPlatform\Resource\GiteaBranchName;
use App\Module\Integration\Infrastructure\Service\GiteaApiService;
use App\Module\ProjectManagement\Domain\Repository\TaskRepositoryInterface;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

final readonly class GiteaBranchNameProvider implements ProviderInterface
{
    /** @see GiteaBranchProcessor::ALLOWED_TYPES */
    private const array ALLOWED_TYPES = ['feature', 'fix', 'refactor', 'hotfix', 'chore'];

    public function __construct(
        private GiteaApiService $giteaApiService,
        private TaskRepositoryInterface $taskRepository,
    ) {}

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): GiteaBranchName
    {
        $task = $this->taskRepository->findById((int) ($uriVariables['taskId'] ?? 0));
        if (null === $task) {
            throw new NotFoundHttpException('Task not found.');
        }

        $type = $uriVariables['type'] ?? 'feature';
        if (!in_array($type, self::ALLOWED_TYPES, true)) {
            throw new BadRequestHttpException('Invalid branch type.');
        }

        $dto       = new GiteaBranchName();
        $dto->name = $this->giteaApiService->generateBranchName($task, $type);

        return $dto;
    }
}
