<?php

declare(strict_types=1);

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

use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Post;
use ApiPlatform\State\ProviderInterface;
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;

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

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): array|GiteaBranch
    {
        if ($operation instanceof Post) {
            return new GiteaBranch();
        }

        $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 {
            $branches = $this->giteaApiService->listBranches($project, $taskCode);
        } catch (GiteaApiException $e) {
            throw new BadRequestHttpException($e->getMessage(), $e);
        }

        $result = [];
        foreach ($branches as $branch) {
            $dto       = new GiteaBranch();
            $dto->name = $branch['name'];

            try {
                $commits      = $this->giteaApiService->listBranchCommits($project, $branch['name']);
                $dto->commits = array_map(static fn (array $c): array => [
                    'sha'     => substr($c['sha'] ?? '', 0, 7),
                    'message' => $c['commit']['message'] ?? '',
                    'author'  => $c['commit']['author']['name'] ?? '',
                    'date'    => $c['commit']['author']['date'] ?? $c['created'] ?? '',
                ], $commits);
            } catch (GiteaApiException) {
                // Commits fetch failure should not block branch listing
                $dto->commits = [];
            }

            $result[] = $dto;
        }

        return $result;
    }
}
