<?php

declare(strict_types=1);

namespace Builder\Core\Http\Controllers\Auth;

use Builder\Core\Foundation\Middleware\BuilderAuth;
use Builder\Core\Http\Requests\Auth\LoginRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;

final class StoreLoginController
{
    public function __invoke(LoginRequest $request): RedirectResponse
    {
        /** @var array{email: string, password: string} $credentials */
        $credentials = $request->validated();

        $guard = BuilderAuth::guard();

        if (Auth::guard($guard)->attempt($credentials)) {
            $request->session()->regenerate();

            return redirect()->route('builder.dashboard');
        }

        return back()
            ->withErrors(['email' => 'These credentials do not match our records.'])
            ->onlyInput('email');
    }
}
