<?php

namespace App\Actions;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class LoginUserAction
{
    /**
     * @param  array{email: string, password: string}  $credentials
     */
    public function handle(Request $request, array $credentials): User
    {
        if (! Auth::guard('web')->attempt($credentials)) {
            throw ValidationException::withMessages([
                'email' => __('auth.failed'),
            ]);
        }

        abort_unless($request->hasSession(), 403, 'Stateful authentication is required.');

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

        $user = $request->user();

        assert($user instanceof User);

        return $user;
    }
}
