<?php

namespace App\Http\Controllers;

use App\Services\NicknameCheckService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class NicknameCheckController extends Controller
{
    private $nicknameService;

    public function __construct(NicknameCheckService $nicknameService)
    {
        $this->nicknameService = $nicknameService;
    }

    public function check(Request $request)
{
    Log::info('🎯 ====== NICKNAME CHECK START ======');
    Log::info('📋 Request Data:', $request->all());
    
    try {
        // ✅ Validate with type checking
        $validated = $request->validate([
            'game_code' => 'required|string',
            'user_id' => 'required|string',
            'zone_id' => 'nullable|string',
            'server' => 'nullable|string',
        ]);
        
        // ✅ Clean inputs
        $gameCode = trim($request->game_code);
        $userId = trim($request->user_id);
        $zoneId = $request->has('zone_id') && is_string($request->zone_id) ? trim($request->zone_id) : null;
        $server = $request->has('server') && is_string($request->server) ? trim($request->server) : null;
        
        // Check if game supports nickname check
        if (!$this->nicknameService->supportsNicknameCheck($gameCode)) {
            Log::warning('⚠️ Game not supported: ' . $gameCode);
            
            return response()->json([
                'success' => false,
                'message' => 'Game ini belum support nickname check',
            ]);
        }
        
        Log::info('🎮 Calling nickname service...', [
            'game_code' => $gameCode,
            'user_id' => $userId,
            'zone_id' => $zoneId,
            'server' => $server,
        ]);
        
        // Call VIP Reseller API
        $result = $this->nicknameService->checkNickname(
            $gameCode,
            $userId,
            $zoneId,
            $server
        );
        
        Log::info('📤 Final Result:', $result);
        Log::info('🏁 ====== NICKNAME CHECK END ======');
        
        return response()->json($result);
        
    } catch (\Illuminate\Validation\ValidationException $e) {
        Log::error('❌ Validation Error:', $e->errors());
        
        return response()->json([
            'success' => false,
            'message' => 'Data input tidak valid',
            'errors' => $e->errors()
        ], 422);
        
    } catch (\Exception $e) {
        Log::error('❌ Nickname Check Controller Error:', [
            'error' => $e->getMessage(),
            'trace' => $e->getTraceAsString(),
        ]);
        
        return response()->json([
            'success' => false,
            'message' => 'Terjadi kesalahan sistem',
        ], 500);
    }
}
}