<?php

declare(strict_types=1);

namespace App\State;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\ApiResource\GiteaBranch;
use App\Entity\Task;
use App\Exception\GiteaApiException;
use App\Service\GiteaApiService;
use Doctrine\ORM\EntityManagerInterface;
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 EntityManagerInterface $em,
    ) {}

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

        $task = $this->em->getRepository(Task::class)->find($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;
    }
}
