<?php

namespace ServerManager\Services;

use LKDev\HetznerCloud\HetznerAPIClient;

class HetznerService
{
    /**
     * Load servers from Hetzner API asynchronously
     * This function is designed to run in a separate thread
     */
    public static function loadServersAsync(string $apiKey): array
    {
        try {
            if (empty($apiKey)) {
                return ['error' => 'Kein API-Key konfiguriert'];
            }

            $hetznerClient = new HetznerAPIClient($apiKey);
            $servers = [];

            foreach ($hetznerClient->servers()->all() as $server) {
                $servers[] = [
                    'id' => $server->id,
                    'name' => $server->name,
                    'status' => $server->status,
                    'type' => $server->serverType->name,
                    'ipv4' => $server->publicNet->ipv4->ip,
                    'docker_status' => 'pending',
                    'domains' => [],
                    'needs_reboot' => 'unbekannt',
                    'updates_available' => 'unbekannt',
                    'os_version' => 'unbekannt',
                    'release' => 'unbekannt',
                    'root' => 'unbekannt',
                    'data' => 'unbekannt',
                    'last_backup' => 'unbekannt',
                    'ssh_keys' => [],
                ];
            }

            return [
                'success' => true,
                'servers' => $servers,
                'count' => count($servers),
            ];
        } catch (\Exception $e) {
            return ['error' => 'Exception: ' . $e->getMessage()];
        }
    }

    /**
     * Generate test server data for development
     */
    public static function generateTestData(int $count = 5): array
    {
        $testData = [];
        for ($i = 1; $i <= $count; $i++) {
            $testData[] = [
                'id' => $i,
                'name' => "Server-{$i}",
                'status' => ($i % 3) === 0 ? 'stopped' : 'running',
                'type' => 'cx' . (11 + (($i % 4) * 10)),
                'ipv4' => sprintf('192.168.%d.%d', floor($i / 255), $i % 255),
                'docker_status' => 'pending',
                'domains' => [],
                'needs_reboot' => 'nein',
                'updates_available' => 'nein',
                'os_version' => 'Ubuntu 22.04 LTS',
                'release' => 'v1.0.0',
                'root' => '35%',
                'data' => '42%',
                'last_backup' => 'unbekannt',
                'ssh_keys' => [],
            ];
        }
        return $testData;
    }
}
