<?php

namespace App\Services;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use GuzzleHttp\Client;
use Illuminate\Support\Str;

class ApiGamesService
{
    private $merchantId;
    private $secretKey;
    private $baseUrl;
    private $signature;
    
    public function __construct()
    {
        $this->merchantId = config('services.apigames.merchant_id');
        $this->secretKey = config('services.apigames.secret_key');
        $this->baseUrl = config('services.apigames.base_url', 'https://v1.apigames.id');
        // Signature: md5(merchant_id + secret_key)
        $this->signature = md5($this->merchantId . $this->secretKey);
    }
    
    public function checkNickname($game, $userId, $zoneId = null)
    {
        try {
            // 1. Ambil kode game yang valid (misal: mobilelegend)
            $gameCode = $this->getValidGameCode($game);
            
            if (!$gameCode) {
                return ['success' => false, 'message' => 'Game tidak didukung untuk cek nickname'];
            }

            // 2. Logic Gabungan ID untuk ML (ID+Zone)
            $payloadId = ($zoneId && $gameCode === 'mobilelegend') ? $userId . $zoneId : $userId;

            $cacheKey = "apigames_nick_{$gameCode}_{$payloadId}";
            if (Cache::has($cacheKey)) return Cache::get($cacheKey);
            
            // 3. FIX URL: Pastikan $gameCode masuk SEBELUM tanda tanya (?)
            // Format: /merchant/{mid}/cek-username/{game_code}?user_id={uid}&signature={sig}
            $endpoint = sprintf(
                "%s/merchant/%s/cek-username/%s",
                rtrim($this->baseUrl, '/'),
                $this->merchantId,
                $gameCode
            );

            $queryParams = http_build_query([
                'user_id'   => $payloadId,
                'signature' => $this->signature
            ]);

            $url = "{$endpoint}?{$queryParams}";
            
            Log::info('ApiGames Request URL: ' . $url);
            
            $client = new Client(['verify' => false, 'timeout' => 15]);
            $response = $client->get($url);
            $data = json_decode($response->getBody()->getContents(), true);
            
            if (isset($data['status']) && $data['status'] == 1 && isset($data['data']['username'])) {
                $result = [
                    'success' => true,
                    'nickname' => $data['data']['username']
                ];
                Cache::put($cacheKey, $result, now()->addHours(12));
                return $result;
            }
            
            return [
                'success' => false, 
                'message' => $data['error_msg'] ?? 'User ID tidak ditemukan atau engine tidak merespon'
            ];
            
        } catch (\Exception $e) {
            Log::error('ApiGames Exception: ' . $e->getMessage());
            return ['success' => false, 'message' => 'Koneksi API Gagal: ' . $e->getMessage()];
        }
    }

    /**
     * Helper untuk memastikan kita dapet string kode tunggal untuk API
     */
    private function getValidGameCode($game)
    {
        $mapping = [
            'mobilelegend' => ['mobile-legends', 'mlbb', 'ml', 'mobile-legend', 'mobilelegend'],
            'freefire'     => ['free-fire', 'ff', 'freefire'],
            'pubgmobile'   => ['pubg-mobile', 'pubgm', 'pubgmobile'],
            'genshin'      => ['genshin-impact', 'gi', 'genshin'],
        ];
        
        $gameSlug = Str::slug($game);

        foreach ($mapping as $validCode => $aliases) {
            foreach ($aliases as $alias) {
                if (str_contains($gameSlug, $alias)) {
                    return $validCode;
                }
            }
        }
        
        // Kalau tidak ada di mapping, coba kirim apa adanya (siapa tau kodenya pas)
        return $game; 
    }
}