<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Providers\RouteServiceProvider;
use App\Services\UserActivityService;
use App\Support\Auth\QuickLoginCookie;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Inertia\Inertia;
use Inertia\Response;

class AuthenticatedSessionController extends Controller
{
    /**
     * Display the login view.
     */
    public function create(Request $request): Response
    {
        $rememberedEmail = QuickLoginCookie::normalize(
            (string) $request->cookie(QuickLoginCookie::COOKIE_NAME, '')
        );

        return Inertia::render('Auth/Login', [
            'canResetPassword' => Route::has('password.request'),
            'status' => session('status'),
            'quickLogin' => [
                'enabled' => $rememberedEmail !== null,
                'identifier' => QuickLoginCookie::maskIdentifier($rememberedEmail),
            ],
        ]);
    }

    /**
     * Handle an incoming authentication request.
     */
    public function store(LoginRequest $request): RedirectResponse
    {
        $request->authenticate();

        $request->session()->regenerate();
        app(UserActivityService::class)->touchLogin($request->user());

        $response = redirect()->intended(RouteServiceProvider::HOME);
        $email = QuickLoginCookie::normalize((string) $request->input('email', ''));
        if ($email !== null) {
            $response->withCookie(
                Cookie::forever(
                    QuickLoginCookie::COOKIE_NAME,
                    $email,
                    '/',
                    null,
                    null,
                    true,
                    false,
                    'lax'
                )
            );
        }

        return $response;
    }

    public function clearRememberedAccount(): RedirectResponse
    {
        return redirect()->route('login')->withCookie(
            Cookie::forget(QuickLoginCookie::COOKIE_NAME, '/', null)
        );
    }

    /**
     * Destroy an authenticated session.
     */
    public function destroy(Request $request): RedirectResponse
    {
        Auth::guard('web')->logout();

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

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

        return redirect('/');
    }
}
