<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Server;
use App\Models\ServerIp;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class SyncHetznerNetworkInfo extends Command
{
    protected $signature = 'hetzner:sync-network';
    protected $description = 'همگام‌سازی اطلاعات شبکه (Netmask, Gateway, rDNS) سرورهای Hetzner';

    private $apiKey;

    public function __construct()
    {
        parent::__construct();
        // ✅ تغییر از api_key به api_token
        $this->apiKey = config('services.hetzner.api_token');
    }

    public function handle()
    {
        $this->info('🔄 شروع همگام‌سازی اطلاعات شبکه Hetzner...');

        // ✅ دریافت سرورهای Hetzner (شامل off هم)
        $servers = Server::where('provider', 'hetzner')
            ->whereNotIn('status', ['deleted', 'failed'])
            ->get();

        if ($servers->isEmpty()) {
            $this->warn('⚠️  سروری یافت نشد!');
            return 0;
        }

        $this->info("✅ {$servers->count()} سرور Hetzner یافت شد");

        $updated = 0;
        $errors = 0;

        foreach ($servers as $server) {
            try {
                $this->info("📡 دریافت اطلاعات سرور: {$server->name} (ID: {$server->provider_id})");

                // دریافت اطلاعات از API
                $response = Http::withHeaders([
                    'Authorization' => 'Bearer ' . $this->apiKey,
                ])->get("https://api.hetzner.cloud/v1/servers/{$server->provider_id}");

                if (!$response->successful()) {
                    $this->error("❌ خطا در دریافت اطلاعات سرور {$server->name}");
                    $this->error("   Status Code: {$response->status()}");
                    $this->error("   Response: " . $response->body());
                    
                    Log::error('Hetzner API Error', [
                        'server_id' => $server->id,
                        'provider_id' => $server->provider_id,
                        'status' => $response->status(),
                        'body' => $response->body(),
                    ]);
                    
                    $errors++;
                    continue;
                }

                $hetzServer = $response->json()['server'] ?? [];

                if (empty($hetzServer)) {
                    $this->warn("⚠️  اطلاعات سرور {$server->name} دریافت نشد");
                    continue;
                }

                // ✅ به‌روزرسانی IP اصلی سرور
                $mainIpv4 = $hetzServer['public_net']['ipv4']['ip'] ?? null;
                if ($server->ip_address !== $mainIpv4) {
                    $server->ip_address = $mainIpv4;
                    $server->save();
                    $this->info("  ✅ IP اصلی سرور به‌روز شد: {$server->ip_address}");
                }

                // ✅ به‌روزرسانی Primary IPv4
                if (isset($hetzServer['public_net']['ipv4'])) {
                    $ipv4Data = $hetzServer['public_net']['ipv4'];
                    
                    $primaryIPv4 = ServerIp::where('server_id', $server->id)
                        ->where('type', 'ipv4')
                        ->where('is_primary', 1)
                        ->first();

                    if ($primaryIPv4) {
                        $updated_fields = [];
                        
                        if ($primaryIPv4->ip !== $ipv4Data['ip']) {
                            $primaryIPv4->ip = $ipv4Data['ip'];
                            $updated_fields[] = 'IP';
                        }
                        
                        $netmask = '255.255.255.255';
                        if ($primaryIPv4->netmask !== $netmask) {
                            $primaryIPv4->netmask = $netmask;
                            $updated_fields[] = 'Netmask';
                        }
                        
                        $gateway = null;
                        if ($primaryIPv4->gateway !== $gateway) {
                            $primaryIPv4->gateway = $gateway;
                            $updated_fields[] = 'Gateway';
                        }

                        $rdns = $ipv4Data['dns_ptr'][0]['dns_ptr'] ?? null;
                        if ($rdns && $primaryIPv4->rdns !== $rdns) {
                            $primaryIPv4->rdns = $rdns;
                            $updated_fields[] = 'RDNS';
                        }

                        if (isset($ipv4Data['id']) && $primaryIPv4->provider_ip_id !== $ipv4Data['id']) {
                            $primaryIPv4->provider_ip_id = $ipv4Data['id'];
                            $updated_fields[] = 'Provider ID';
                        }

                        if (isset($hetzServer['datacenter']['location']['name'])) {
                            if ($primaryIPv4->location !== $hetzServer['datacenter']['location']['name']) {
                                $primaryIPv4->location = $hetzServer['datacenter']['location']['name'];
                                $updated_fields[] = 'Location';
                            }
                        }

                        if (isset($hetzServer['datacenter']['name'])) {
                            if ($primaryIPv4->datacenter !== $hetzServer['datacenter']['name']) {
                                $primaryIPv4->datacenter = $hetzServer['datacenter']['name'];
                                $updated_fields[] = 'Datacenter';
                            }
                        }

                        if (!empty($updated_fields)) {
                            $primaryIPv4->save();
                            $this->info("  ✅ IPv4 به‌روز شد: " . implode(', ', $updated_fields));
                            $updated++;
                        }
                    } else {
                        // ایجاد IPv4 جدید
                        ServerIp::create([
                            'server_id' => $server->id,
                            'user_id' => $server->user_id,
                            'ip' => $ipv4Data['ip'],
                            'type' => 'ipv4',
                            'is_primary' => 1,
                            'is_floating' => 0,
                            'assigned_at' => now(),
                            'status' => 'active',
                            'provider' => 'hetzner',
                            'provider_ip_id' => $ipv4Data['id'] ?? null,
                            'location' => $hetzServer['datacenter']['location']['name'] ?? $server->region,
                            'datacenter' => $hetzServer['datacenter']['name'] ?? null,
                            'hourly_cost' => 250,
                            'netmask' => '255.255.255.255',
                            'gateway' => null,
                            'rdns' => $ipv4Data['dns_ptr'][0]['dns_ptr'] ?? null,
                        ]);
                        $this->info("  ✅ IPv4 جدید ایجاد شد: {$ipv4Data['ip']}");
                        $updated++;
                    }
                }

                // ✅ به‌روزرسانی Primary IPv6
                if (isset($hetzServer['public_net']['ipv6'])) {
                    $ipv6Data = $hetzServer['public_net']['ipv6'];
                    
                    $primaryIPv6 = ServerIp::where('server_id', $server->id)
                        ->where('type', 'ipv6')
                        ->where('is_primary', 1)
                        ->first();

                    if ($primaryIPv6) {
                        $updated_v6 = [];
                        
                        if ($primaryIPv6->ip !== $ipv6Data['ip']) {
                            $primaryIPv6->ip = $ipv6Data['ip'];
                            $updated_v6[] = 'IP';
                        }
                        
                        $netmask = '/' . ($ipv6Data['network_size'] ?? 64);
                        if ($primaryIPv6->netmask !== $netmask) {
                            $primaryIPv6->netmask = $netmask;
                            $updated_v6[] = 'Netmask';
                        }

                        $gateway = $ipv6Data['network'] ?? null;
                        if ($primaryIPv6->gateway !== $gateway) {
                            $primaryIPv6->gateway = $gateway;
                            $updated_v6[] = 'Gateway';
                        }

                        $rdns = $ipv6Data['dns_ptr'][0]['dns_ptr'] ?? null;
                        if ($rdns && $primaryIPv6->rdns !== $rdns) {
                            $primaryIPv6->rdns = $rdns;
                            $updated_v6[] = 'RDNS';
                        }

                        if (isset($ipv6Data['id']) && $primaryIPv6->provider_ip_id !== $ipv6Data['id']) {
                            $primaryIPv6->provider_ip_id = $ipv6Data['id'];
                            $updated_v6[] = 'Provider ID';
                        }

                        if (!empty($updated_v6)) {
                            $primaryIPv6->save();
                            $this->info("  ✅ IPv6 به‌روز شد: " . implode(', ', $updated_v6));
                            $updated++;
                        }
                    } else {
                        // ایجاد IPv6 جدید
                        ServerIp::create([
                            'server_id' => $server->id,
                            'user_id' => $server->user_id,
                            'ip' => $ipv6Data['ip'],
                            'type' => 'ipv6',
                            'is_primary' => 1,
                            'is_floating' => 0,
                            'assigned_at' => now(),
                            'status' => 'active',
                            'provider' => 'hetzner',
                            'provider_ip_id' => $ipv6Data['id'] ?? null,
                            'location' => $hetzServer['datacenter']['location']['name'] ?? $server->region,
                            'datacenter' => $hetzServer['datacenter']['name'] ?? null,
                            'hourly_cost' => 120,
                            'netmask' => '/' . ($ipv6Data['network_size'] ?? 64),
                            'gateway' => $ipv6Data['network'] ?? null,
                            'rdns' => $ipv6Data['dns_ptr'][0]['dns_ptr'] ?? null,
                        ]);
                        $this->info("  ✅ IPv6 جدید ایجاد شد: {$ipv6Data['ip']}");
                        $updated++;
                    }
                }

                // ✅ همگام‌سازی Floating IPs
                $this->syncHetznerFloatingIPs($server);

            } catch (\Exception $e) {
                $this->error("❌ خطا در پردازش سرور {$server->name}: {$e->getMessage()}");
                Log::error('Hetzner Sync Network Error', [
                    'server_id' => $server->id,
                    'error' => $e->getMessage(),
                    'trace' => $e->getTraceAsString(),
                ]);
                $errors++;
            }
        }

        $this->info("\n✅ همگام‌سازی تمام شد!");
        $this->info("📊 تعداد به‌روزرسانی: {$updated}");
        $this->info("❌ تعداد خطا: {$errors}");

        return 0;
    }

    /**
     * همگام‌سازی Floating IPs
     */
    private function syncHetznerFloatingIPs($server)
    {
        try {
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $this->apiKey,
            ])->get('https://api.hetzner.cloud/v1/floating_ips');

            if (!$response->successful()) {
                return;
            }

            $floatingIps = $response->json()['floating_ips'] ?? [];

            foreach ($floatingIps as $floatingIp) {
                if (isset($floatingIp['server']) && $floatingIp['server'] == $server->provider_id) {
                    
                    $existingFloating = ServerIp::where('server_id', $server->id)
                        ->where('ip', $floatingIp['ip'])
                        ->where('is_floating', 1)
                        ->first();

                    if (!$existingFloating) {
                        ServerIp::create([
                            'server_id' => $server->id,
                            'user_id' => $server->user_id,
                            'ip' => $floatingIp['ip'],
                            'type' => $floatingIp['type'],
                            'is_primary' => 0,
                            'is_floating' => 1,
                            'assigned_at' => now(),
                            'status' => 'active',
                            'provider' => 'hetzner',
                            'provider_ip_id' => $floatingIp['id'],
                            'location' => $floatingIp['home_location']['name'] ?? null,
                            'hourly_cost' => 400,
                            'rdns' => $floatingIp['dns_ptr'][0]['dns_ptr'] ?? null,
                        ]);
                        
                        $this->info("  ✅ Floating IP جدید: {$floatingIp['ip']}");
                    }
                }
            }
        } catch (\Exception $e) {
            Log::error('Hetzner Floating IP Sync Error', [
                'server_id' => $server->id,
                'error' => $e->getMessage(),
            ]);
        }
    }
}