<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class AuthController extends Controller
{
    /**
     * POST /api/login
     * Exchange a Discord OAuth token for a Sanctum token.
     * Used by the Desktop Launcher.
     */
    public function login(Request $request)
    {
        $request->validate([
            'discord_token' => ['required_without:steam_id', 'string', 'nullable'],
            'steam_id'      => ['required_without:discord_token', 'string', 'nullable'],
        ]);

        // ── Login via Steam ID (sudah diverifikasi launcher-side) ──────────
        if ($request->filled('steam_id')) {
            return $this->loginWithSteam($request->steam_id);
        }

        // ── Login via Discord token ────────────────────────────────────────
        return $this->loginWithDiscord($request->discord_token);
    }

    private function loginWithDiscord(string $discordToken)
    {
        $response = Http::withToken($discordToken)
            ->get('https://discord.com/api/users/@me');

        if (! $response->ok()) {
            return response()->json(['message' => 'Invalid Discord token'], 401);
        }

        $discordUser = $response->json();

        $avatarUrl = isset($discordUser['avatar'])
            ? "https://cdn.discordapp.com/avatars/{$discordUser['id']}/{$discordUser['avatar']}.png?size=256"
            : null;

        $user = User::updateOrCreate(
            ['discord_id' => $discordUser['id']],
            [
                'username'         => $discordUser['global_name'] ?? $discordUser['username'],
                'discord_username' => $discordUser['username'],
                'avatar'           => $avatarUrl,
                'email'            => $discordUser['email'] ?? null,
            ]
        );

        return $this->issueToken($user);
    }

    private function loginWithSteam(string $steamId)
    {
        // Verifikasi Steam ID ke Steam Web API
        $apiKey = config('services.steam.client_secret');

        if ($apiKey) {
            $response = Http::get('https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/', [
                'key'      => $apiKey,
                'steamids' => $steamId,
            ]);

            if (! $response->ok() || empty($response->json('response.players'))) {
                return response()->json(['message' => 'Invalid Steam ID'], 401);
            }

            $steamPlayer = $response->json('response.players.0');
            $username    = $steamPlayer['personaname'] ?? 'Player';
            $avatar      = $steamPlayer['avatarfull'] ?? null;
        } else {
            // Fallback jika API key belum diset (dev only)
            $username = 'SteamPlayer';
            $avatar   = null;
        }

        $user = User::firstOrCreate(
            ['steam_id' => $steamId],
            [
                'username'       => $username,
                'steam_username' => $username,
                'avatar'         => $avatar,
            ]
        );

        // Update avatar & username terbaru dari Steam
        if ($apiKey) {
            $user->update(['steam_username' => $username, 'avatar' => $avatar ?? $user->avatar]);
        }

        return $this->issueToken($user);
    }

    private function issueToken(User $user)
    {
        if ($user->is_banned) {
            return response()->json(['message' => 'Account suspended: ' . $user->ban_reason], 403);
        }

        $user->tokens()->where('name', 'launcher')->delete();
        $token = $user->createToken('launcher')->plainTextToken;

        $div = getDivision($user->elo);

        return response()->json([
            'token' => $token,
            'user'  => [
                'id'            => $user->id,
                'username'      => $user->username,
                'avatar'        => $user->avatar,
                'elo'           => $user->elo,
                'division'      => $div['name'],
                'wins'          => $user->wins,
                'losses'        => $user->losses,
                'draws'         => $user->draws,
                'has_discord'   => (bool) $user->discord_id,
                'has_steam'     => (bool) $user->steam_id,
            ],
        ]);
    }
}
