<?php

declare(strict_types=1);

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

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

final readonly class GiteaPullRequestProvider implements ProviderInterface
{
    public function __construct(
        private GiteaApiService $giteaApiService,
        private TaskRepositoryInterface $taskRepository,
    ) {}

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): array
    {
        $task = $this->taskRepository->findById((int) ($uriVariables['taskId'] ?? 0));
        if (null === $task || null === $task->getProject()) {
            return [];
        }

        $project = $task->getProject();
        if (!$project->hasGiteaRepo()) {
            return [];
        }

        $taskCode = $project->getCode().'-'.$task->getNumber();

        try {
            $prs = $this->giteaApiService->listPullRequests($project, $taskCode);
        } catch (GiteaApiException $e) {
            throw new BadRequestHttpException($e->getMessage(), $e);
        }

        return array_map(static function (array $pr): GiteaPullRequest {
            $dto             = new GiteaPullRequest();
            $dto->number     = $pr['number'] ?? 0;
            $dto->title      = $pr['title'] ?? '';
            $dto->state      = $pr['state'] ?? '';
            $dto->merged     = $pr['merged'] ?? false;
            $dto->headBranch = $pr['head']['ref'] ?? '';
            $dto->author     = $pr['user']['login'] ?? '';
            $dto->url        = $pr['html_url'] ?? '';
            $dto->ciStatuses = array_map(static fn (array $s): array => [
                'context'    => $s['context'] ?? '',
                'status'     => $s['status'] ?? '',
                'target_url' => $s['target_url'] ?? '',
            ], $pr['ci_statuses'] ?? []);

            return $dto;
        }, $prs);
    }
}
