<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use App\Models\Pouzivatel\Authentication;
use Closure;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Support\Facades\Auth;
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.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $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);
    }
}
