<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;
use Inertia\Response;
use Laravel\Socialite\Facades\Socialite;

class AuthController extends Controller
{
    /**
     * Zeige die Login-Seite.
     */
    public function showLogin(): Response
    {
        return Inertia::render('Auth/Login', [
            'canDevLogin' => app()->environment('local', 'testing'),
        ]);
    }

    /**
     * Leite den Benutzer zu ChurchTools OAuth weiter.
     */
    public function redirect(): RedirectResponse|\Symfony\Component\HttpFoundation\RedirectResponse
    {
        return Socialite::driver('churchtools')->redirect();
    }

    /**
     * Verarbeite den OAuth-Callback von ChurchTools.
     */
    public function callback(): RedirectResponse
    {
        $socialiteUser = Socialite::driver('churchtools')->user();
        $rawUser = $socialiteUser->user ?? [];

        $user = User::updateOrCreate(
            ['email' => $socialiteUser->getEmail()],
            [
                'name' => $socialiteUser->getName(),
                'churchtools_id' => (int) ($rawUser['id'] ?? $socialiteUser->getId()),
                'avatar' => $socialiteUser->getAvatar() ?? ($rawUser['imageUrl'] ?? null),
                'churchtools_groups' => $rawUser['groups'] ?? [],
                'churchtools_roles' => $rawUser['roles'] ?? [],
                'password' => '',
            ],
        );

        Auth::login($user, remember: true);

        return redirect()->intended(route('dashboard'));
    }

    /**
     * Melde den Benutzer ab.
     */
    public function logout(Request $request): RedirectResponse
    {
        Auth::guard('web')->logout();

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

        return redirect('/login');
    }
}
