<?php

declare(strict_types=1);

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Role;
use App\Models\User;
use App\Services\ActivityLogger;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
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()->updateOrCreate(
            ['email' => $azureUser->getEmail()],
            [
                'name' => $azureUser->getName(),
                'azure_id' => $azureUser->getId(),
                'photo' => $azureUser->getAvatar(),
                'job_title' => Arr::get($azureUser->user, 'jobTitle'),
                'department' => Arr::get($azureUser->user, 'department'),
                'company_name' => Arr::get($azureUser->user, 'companyName'),
                'phone' => Arr::get($azureUser->user, 'mobilePhone', Arr::get($azureUser->user, 'businessPhones.0')),
            ]
        );

        if ($user->role_id === null) {
            $user->update(['role_id' => Role::where('name', 'user')->first()->id]);
        }

        auth()->login($user);

        ActivityLogger::log('login', $user->id, metadata: ['email' => $user->email, 'firm_name' => Arr::get($azureUser->user, 'companyName')]);

        return redirect('/');
    }

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

        auth()->logout();

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

        return redirect('/');
    }
}
