<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;

class SteamController extends Controller
{
    /**
     * Redirect ke Steam OpenID.
     */
    public function redirect(): RedirectResponse
    {
        return Socialite::driver('steam')->redirect();
    }

    /**
     * Handle Steam callback.
     *
     * Tiga skenario:
     *   A) User sudah login → link akun Steam ke akun yang sedang aktif.
     *   B) User belum login, Steam ID sudah ada di DB → langsung login.
     *   C) User belum login, Steam ID belum ada → buat akun baru via Steam.
     */
    public function callback(): RedirectResponse
    {
        try {
            $steamUser = Socialite::driver('steam')->user();
        } catch (\Exception $e) {
            return redirect()->route('login')->with('error', 'Steam login gagal. Silakan coba lagi.');
        }

        $steamId       = (string) $steamUser->getId();
        $steamUsername = $steamUser->getNickname() ?? $steamUser->getName();
        $steamAvatar   = $steamUser->getAvatar();

        // ── Skenario A: User sudah login, ingin link Steam ─────────────────
        if (Auth::check()) {
            $currentUser = Auth::user();

            // Cek apakah Steam ID ini sudah dipakai akun lain
            $existing = User::where('steam_id', $steamId)
                            ->where('id', '!=', $currentUser->id)
                            ->first();

            if ($existing) {
                return redirect()->route('profile.show')
                    ->with('error', 'Akun Steam ini sudah terhubung ke akun lain.');
            }

            $currentUser->update([
                'steam_id'       => $steamId,
                'steam_username' => $steamUsername,
            ]);

            return redirect()->route('profile.show')
                ->with('success', 'Akun Steam berhasil dihubungkan!');
        }

        // ── Skenario B: Steam ID sudah ada → login langsung ───────────────
        $user = User::where('steam_id', $steamId)->first();

        if ($user) {
            if ($user->is_banned) {
                return redirect()->route('login')
                    ->with('error', 'Akun kamu di-suspend. Alasan: ' . ($user->ban_reason ?? 'N/A'));
            }

            Auth::login($user, remember: true);
            return redirect()->intended(route('dashboard'));
        }

        // ── Skenario C: Akun baru via Steam ───────────────────────────────
        $user = User::create([
            'username'       => $steamUsername,
            'steam_id'       => $steamId,
            'steam_username' => $steamUsername,
            'avatar'         => $steamAvatar,
        ]);

        Auth::login($user, remember: true);
        return redirect()->route('dashboard')->with('success', 'Selamat datang di PES League, ' . $user->username . '!');
    }

    /**
     * Hapus koneksi Steam dari akun yang sedang login.
     */
    public function unlink(): RedirectResponse
    {
        $user = Auth::user();

        // Harus punya minimal satu metode login
        if (! $user->discord_id) {
            return redirect()->route('profile.show')
                ->with('error', 'Kamu tidak bisa melepas Steam karena tidak ada akun Discord yang terhubung.');
        }

        $user->update(['steam_id' => null, 'steam_username' => null]);

        return redirect()->route('profile.show')
            ->with('success', 'Koneksi Steam berhasil dilepas.');
    }
}
