<?php

declare(strict_types=1);

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

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Module\Integration\Domain\Exception\GiteaApiException;
use App\Module\Integration\Infrastructure\ApiPlatform\Resource\GiteaBranch;
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 GiteaBranchProcessor implements ProcessorInterface
{
    private const array ALLOWED_TYPES = ['feature', 'fix', 'refactor', 'hotfix', 'chore'];

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

    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): GiteaBranch
    {
        assert($data instanceof GiteaBranch);

        $task = $this->taskRepository->findById((int) ($uriVariables['taskId'] ?? 0));
        if (null === $task || null === $task->getProject()) {
            throw new NotFoundHttpException('Task not found.');
        }

        $project = $task->getProject();
        if (!$project->hasGiteaRepo()) {
            throw new BadRequestHttpException('Project has no Gitea repository.');
        }

        if (!in_array($data->type, self::ALLOWED_TYPES, true)) {
            throw new BadRequestHttpException('Invalid branch type.');
        }

        try {
            $branchName = $this->giteaApiService->createBranch($project, $task, $data->type, $data->baseBranch);
        } catch (GiteaApiException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        $result       = new GiteaBranch();
        $result->name = $branchName;

        return $result;
    }
}
