<?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\GiteaRepository;
use App\Module\Integration\Infrastructure\Service\GiteaApiService;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

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

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): array
    {
        try {
            $repos = $this->giteaApiService->listRepositories();
        } catch (GiteaApiException $e) {
            throw new BadRequestHttpException($e->getMessage(), $e);
        }

        return array_map(static function (array $repo): GiteaRepository {
            $dto           = new GiteaRepository();
            $dto->fullName = $repo['full_name'] ?? '';
            $dto->name     = $repo['name'] ?? '';
            $dto->owner    = $repo['owner']['login'] ?? '';

            return $dto;
        }, $repos);
    }
}
