<?php

declare(strict_types=1);

namespace App\Http\Controllers\Auth;

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

final class SocialiteController extends Controller
{
    /**
     * Redirect the user to the Azure AD authentication page.
     */
    public function redirect(): RedirectResponse
    {
        return Socialite::driver('azure')->redirect();
    }

    /**
     * Handle the callback from Azure AD after authentication.
     */
    public function callback(): RedirectResponse
    {
        $azureUser = Socialite::driver('azure')->user();

        $user = User::query()->firstOrCreate(
            ['email' => $azureUser->getEmail()],
            [
                'name' => $azureUser->getName(),
                'password' => null,
            ]
        );

        auth()->login($user);

        return redirect('/');
    }

    /**
     * Log the user out and redirect to landing page.
     */
    public function logout(Request $request): RedirectResponse
    {
        auth()->logout();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/');
    }
}
