<?php

use App\Http\Controllers\Auth\AuthenticatedSessionController;
use App\Http\Controllers\Auth\RegisteredUserController;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use Laravel\Socialite\Facades\Socialite;

Route::get('/auth/redirect', function () {
    return Socialite::driver('keycloak')->redirect();
})->name('auth.redirect');

Route::get('/auth/callback', function () {
    $keycloackUser = Socialite::driver('keycloak')->user();

    $user = User::where('oidc_id', $keycloackUser->getId())->first();

    if ($user) {
        Auth::login($user);
        return redirect()->intended(route('home'));
    } else {
        $user = User::create([
            'email' => $keycloackUser->getEmail(),
            'name' => $keycloackUser->getNickname(),
            'avatar' => $keycloackUser->getAvatar(),
            'oidc_id' => $keycloackUser->getId()
        ]);
        Auth::login($user);
        return redirect()->intended(route('home'));
    }
});
