<?php

declare(strict_types=1);

namespace PHPNative\Framework;

class HetznerClient
{
    private string $apiToken;
    private string $baseUrl = 'https://api.hetzner.cloud/v1';

    public function __construct(string $apiToken)
    {
        $this->apiToken = $apiToken;
    }

    /**
     * Fetch all servers from Hetzner Cloud API
     * @return array Array of server data or error
     */
    public function getServers(): array
    {
        $ch = curl_init($this->baseUrl . '/servers');

        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $this->apiToken,
                'Content-Type: application/json',
            ],
            CURLOPT_TIMEOUT => 10,
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);

        if ($error) {
            return ['error' => 'cURL Error: ' . $error];
        }

        if ($httpCode !== 200) {
            return ['error' => 'HTTP Error ' . $httpCode . ': ' . $response];
        }

        $data = json_decode($response, true);

        if (!$data || !isset($data['servers'])) {
            return ['error' => 'Invalid API response'];
        }

        // Transform server data for table display
        $servers = [];
        foreach ($data['servers'] as $server) {
            $servers[] = [
                'id' => $server['id'] ?? '-',
                'name' => $server['name'] ?? '-',
                'status' => $server['status'] ?? '-',
                'type' => $server['server_type']['name'] ?? '-',
                'location' => $server['datacenter']['location']['city'] ?? '-',
                'ipv4' => $server['public_net']['ipv4']['ip'] ?? '-',
            ];
        }

        return ['servers' => $servers];
    }
}
