<?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;

/**
 * Session-based authentication for the admin app.
 * MFA, password reset, super-admin enforcement, role-permission checks etc.
 * are deferred — see docs/features/auth-users.md for the full spec.
 */
class LoginController extends Controller
{
    public function show(): View|RedirectResponse
    {
        return Auth::check()
            ? redirect()->intended('/admin')
            : view('auth.login');
    }

    public function attempt(LoginRequest $request): RedirectResponse|JsonResponse
    {
        $request->ensureIsNotRateLimited();

        $credentials = $request->only('email', 'password');
        $remember    = $request->boolean('remember');

        if (! Auth::attempt($credentials, $remember)) {
            $request->hitRateLimit();

            if ($request->expectsJson()) {
                return response()->json([
                    'message' => __('auth.failed'),
                    'errors'  => ['email' => [__('auth.failed')]],
                ], 422);
            }

            return back()
                ->withErrors(['email' => __('auth.failed')])
                ->withInput($request->only('email', 'remember'));
        }

        $request->clearRateLimit();
        $request->session()->regenerate();

        if ($request->expectsJson()) {
            $intended = session()->pull('url.intended', '/admin');
            return response()->json(['redirect' => $intended]);
        }

        return redirect()->intended('/admin');
    }

    public function destroy(Request $request): RedirectResponse
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/login');
    }
}
