<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

class AuthenticatedSessionController extends Controller
{
    protected const CAPTCHA_TTL_SECONDS = 60;

    /**
     * Display the login view.
     */
    public function create(Request $request): View
    {
        return view('auth.login', $this->generateCaptcha($request));
    }

    /**
     * Refresh the login challenge.
     */
    public function refreshCaptcha(Request $request): JsonResponse
    {
        return response()
            ->json($this->generateCaptcha($request))
            ->header('Cache-Control', 'no-store, no-cache, must-revalidate');
    }

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

        $request->session()->regenerate();
        $request->session()->forget([
            'login_captcha_question',
            'login_captcha_answer',
        ]);

        return redirect()->intended(route('dashboard', absolute: false));
    }

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

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

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

        return redirect('/');
    }

    protected function generateCaptcha(Request $request): array
    {
        $left = random_int(2, 9);
        $right = random_int(1, 8);

        $request->session()->put('login_captcha_question', "{$left} + {$right}");
        $request->session()->put('login_captcha_answer', (string) ($left + $right));
        $request->session()->put('login_captcha_generated_at', now()->timestamp);

        return [
            'captchaQuestion' => "{$left} + {$right}",
            'captchaExpiresIn' => self::CAPTCHA_TTL_SECONDS,
        ];
    }
}
