<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class NicknameService
{
    /**
     * Main handler for validation based on game
     */
    public function check($game, $userId, $zoneId = null)
    {
        $game = strtolower($game);

        if (str_contains($game, 'mobile legends')) {
            return $this->checkMobileLegends($userId, $zoneId);
        }

        if (str_contains($game, 'free fire')) {
            return $this->checkFreeFire($userId);
        }

        if (str_contains($game, 'genshin')) {
            return $this->checkGenshinImpact($userId, $zoneId);
        }

        if (str_contains($game, 'honor of kings') || str_contains($game, 'hok')) {
            return $this->checkHonorOfKings($userId);
        }

        // Add more games as needed...
        
        return [
            'success' => true,
            'nickname' => 'CustomerID-' . substr($userId, 0, 4)
        ];
    }

    /**
     * Mobile Legends Check
     */
    private function checkMobileLegends($userId, $zoneId)
    {
        if (!$zoneId) return ['success' => false, 'message' => 'Zone ID diperlukan untuk Mobile Legends.'];

        try {
            // Karena API gratisan sering mati, kita buat timeout jadi 3 detik agar tidak lemot
            $response = Http::timeout(4)->get("https://api.kyandev.my.id/api/game/ml", [
                'id' => $userId,
                'zone' => $zoneId
            ]);

            if ($response->successful()) {
                $data = $response->json();
                if (isset($data['nickname']) || isset($data['data']['userName'])) {
                    return [
                        'success' => true,
                        'nickname' => $data['nickname'] ?? $data['data']['userName']
                    ];
                }
            }
        } catch (\Exception $e) {
            Log::error("[NICKNAME ERROR] ML API Down: " . $e->getMessage());
        }

        // Jika API pihak ketiga mati, kita kembalikan false agar Frontend bisa bertindak!
        return [
            'success' => false, 
            'message' => 'Layanan Pengecek Nama sedang sibuk'
        ];
    }

    /**
     * Free Fire Check
     */
    private function checkFreeFire($userId)
    {
        try {
            $response = Http::timeout(4)->get("https://api.kyandev.my.id/api/game/ff", [
                'id' => $userId
            ]);

            if ($response->successful()) {
                $data = $response->json();
                if (isset($data['nickname']) || isset($data['data']['username'])) {
                    return [
                        'success' => true,
                        'nickname' => $data['nickname'] ?? $data['data']['username']
                    ];
                }
            }
        } catch (\Exception $e) {
            // Abaikan error
        }

        // Jika API pihak ketiga mati, kembalikan false!
        return [
            'success' => false, 
             'message' => 'Layanan Pengecek Nama sedang sibuk'
        ];
    }

    /**
     * Genshin Impact Check
     */
    private function checkGenshinImpact($userId, $zoneId)
    {
        if (!$zoneId) return ['success' => false, 'message' => 'Server ID diperlukan.'];
        
        // Example logic for Genshin...
        return ['success' => true, 'nickname' => 'Traveler-' . substr($userId, -4)];
    }

    /**
     * Honor of Kings Check
     */
    private function checkHonorOfKings($userId)
    {
        try {
            // Check into public validation API
            $response = Http::timeout(10)->get("https://api.kyandev.my.id/api/game/hok", [
                'id' => $userId
            ]);

            if ($response->successful()) {
                $data = $response->json();
                if (isset($data['nickname']) || isset($data['data']['username'])) {
                    return [
                        'success' => true,
                        'nickname' => $data['nickname'] ?? $data['data']['username']
                    ];
                }
            }

            return ['success' => false, 'message' => 'ID Honor of Kings tidak ditemukan. Harap periksa kembali.'];
        } catch (\Exception $e) {
            return ['success' => false, 'message' => 'Gagal terhubung ke modul Honor of Kings.'];
        }
    }
}
