<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use App\Models\Pouzivatel\Authentication;
use Closure;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;

/**
 * Class BasicAuthenticate
 */
class BasicAuthenticate
{
    private Authentication $authentication;

    public function __construct(Authentication $authentication)
    {
        $this->authentication = $authentication;
    }

    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $credentials = [
            'login' => $request->getUser(),
            'password' => $request->getPassword(),
        ];

        try {
            $this->authentication->auth($credentials);
        } catch (AuthenticationException $exception) {
            throw new HttpException(401, $exception->getMessage());
        }

        Auth::guard()->once($credentials);

        return $next($request);
    }
}
