<?php

declare(strict_types=1);

namespace App\Infrastructure\Api;

use App\Framework\Api\ApiRequestTrait;
use App\Framework\Http\Method;
use App\Framework\HttpClient\AuthConfig;
use App\Framework\HttpClient\ClientOptions;
use App\Framework\HttpClient\CurlHttpClient;
use App\Framework\HttpClient\HttpClient;

final class GitHubClient
{
    use ApiRequestTrait;

    public function __construct(
        string $token,
        ?HttpClient $httpClient = null
    ) {
        $this->baseUrl = 'https://api.github.com';
        $this->defaultOptions = new ClientOptions(
            auth: AuthConfig::bearer($token)
        );
        $this->httpClient = $httpClient ?? new CurlHttpClient();

        // GitHub API spezifische Header setzen
        $this->defaultOptions = new ClientOptions(
            auth: AuthConfig::bearer($token),
            userAgent: 'PHP-App-Framework'
        );
    }

    /**
     * Holt Repositories eines Benutzers
     */
    public function getUserRepositories(string $username): array
    {
        $response = $this->sendRequest(
            method: Method::GET,
            endpoint: "users/{$username}/repos"
        );

        return $this->decodeJson($response);
    }

    /**
     * Erstellt ein neues Repository
     */
    public function createRepository(string $name, string $description = '', bool $isPrivate = false): array
    {
        $response = $this->sendRequest(
            method: Method::POST,
            endpoint: 'user/repos',
            data: [
                'name' => $name,
                'description' => $description,
                'private' => $isPrivate,
            ]
        );

        return $this->decodeJson($response);
    }

    /**
     * Ruft Informationen zu einem bestimmten Repository ab
     */
    public function getRepository(string $owner, string $repo): array
    {
        $response = $this->sendRequest(
            method: Method::GET,
            endpoint: "repos/{$owner}/{$repo}"
        );

        return $this->decodeJson($response);
    }
}
