<?php

namespace App\Http\Controllers\Auth;

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

class SteamAuthController extends Controller
{
    /**
     * Redirect the user to the Steam authentication page.
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function redirect()
    {
        return Socialite::driver('steam')->redirect();
    }

    /**
     * Obtain the user information from Steam.
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function callback()
    {
        try {
            $steamUser = Socialite::driver('steam')->user();
            
            $userData = [
                'steamid' => $steamUser->id,
                'name' => $steamUser->nickname,
                'avatar' => $steamUser->avatar,
            ];
            
            $user = User::findOrCreateBySteamId($userData);

            // Assign role if not already assigned
            if (!$user->hasAnyRole(['super-admin', 'member'])) {
                if (User::count() === 1) {
                    $user->assignRole('super-admin');
                } else {
                    $user->assignRole('member');
                }
            }

            Auth::login($user, true);

            return redirect()->route('home')->with('success', 'Successfully logged in with Steam!');
        } catch (\Exception $e) {
            return redirect()->route('home')->with('error', 'Steam authentication failed: ' . $e->getMessage());
        }
    }


    /**
     * Log the user out.
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function logout(Request $request)
    {
        Auth::logout();
        
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        
        return redirect()->route('home')->with('success', 'Successfully logged out!');
    }
}