<?php
namespace App\Controllers;

class Gitea extends BaseController
{
    private $baseUrl = 'https://gitea.services-summit.my.id/api/v1';

    /**
     * Method helper private untuk menangani semua request cURL ke Gitea
     */
    private function fetchFromGitea(string $endpoint)
    {
        $token = env('GITEA_TOKEN') ?: '0eca3f7e42e0992ecc9af9d947bbbd7cfc6ce2e1';
        $url = $this->baseUrl . $endpoint;

        $client = \Config\Services::curlrequest();

        try {
            $response = $client->request('GET', $url, [
                'headers' => [
                    'Authorization' => "token {$token}",
                    'Accept'        => 'application/json',
                ],
                'http_errors' => false,
            ]);

            if ($response->getStatusCode() !== 200) {
                // Return array dengan format error yang standar
                return [
                    'success' => false,
                    'message' => "Gagal mengambil data dari API. Status: " . $response->getStatusCode(),
                    'data'    => null
                ];
            }

            // Return sukses dengan data yang sudah di-decode
            return [
                'success' => true,
                'message' => 'Data berhasil diambil',
                'data'    => json_decode($response->getBody(), true)
            ];

        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => "Terjadi kesalahan cURL: " . $e->getMessage(),
                'data'    => null
            ];
        }
    }

    /**
     * Mengambil daftar Commits
     * Contoh penggunaan di routes: /gitea/commits/mikael-zakaria/cobazaka
     */
    // public function getCommits(string $owner, string $repo)
    // {
    //     // Tangkap parameter branch jika ada (misal: ?sha=main)
    //     $branch = $this->request->getGet('sha');
        
    //     $endpoint = "/repos/{$owner}/{$repo}/commits";
    //     if (!empty($branch)) {
    //         $endpoint .= "?sha=" . urlencode($branch);
    //     }

    //     $result = $this->fetchFromGitea($endpoint);
    //     return $this->response->setJSON($result);
    // }
    public function getCommits(string $owner, string $repo)
    {
        // Tangkap parameter query string dari JavaScript
        $branch = $this->request->getGet('sha');
        
        // Atur default limit, misalnya 50 (maksimal biasanya tergantung setingan admin Gitea, umumnya 50-100)
        $limit  = $this->request->getGet('limit') ?? 50; 
        $page   = $this->request->getGet('page') ?? 1;

        // Susun parameter API
        $queryParams = [
            'limit' => $limit,
            'page'  => $page
        ];

        // Jika branch dipilih, tambahkan ke parameter
        if (!empty($branch)) {
            $queryParams['sha'] = $branch;
        }

        // Gabungkan endpoint dengan query string
        $endpoint = "/repos/{$owner}/{$repo}/commits?" . http_build_query($queryParams);

        $result = $this->fetchFromGitea($endpoint);
        return $this->response->setJSON($result);
    }

    /**
     * Mengambil daftar Branches
     * Contoh penggunaan di routes: /gitea/branches/mikael-zakaria/cobazaka
     */
    public function getBranches(string $owner, string $repo)
    {
        $endpoint = "/repos/{$owner}/{$repo}/branches";
        $result = $this->fetchFromGitea($endpoint);

        return $this->response->setJSON($result);
    }

    /**
     * Mengambil detail User
     * Contoh penggunaan di routes: /gitea/user/mikael-zakaria
     */
    public function getUser(string $username)
    {
        $endpoint = "/users/{$username}";
        $result = $this->fetchFromGitea($endpoint);

        return $this->response->setJSON($result);
    }

	/**
     * Mengambil daftar Repositori milik User
     * Contoh penggunaan di routes: /gitea/repos/mikael-zakaria
     */
    public function getRepositories(string $username)
    {
        $endpoint = "/users/{$username}/repos";
        $result = $this->fetchFromGitea($endpoint);

        return $this->response->setJSON($result);
    }

    public function index()
    {
        return view('gitea_index');
    }
}