<?php

declare(strict_types=1);

namespace App\Http\Middleware;

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

/**
 * Class BasicAuthenticate
 *
 * @package App\Http\Middleware
 */
class BasicAuthenticate
{
    /**
     * @var \App\Models\Pouzivatel\Authentication
     */
    private Authentication $authentication;

    /**
     * @param \App\Models\Pouzivatel\Authentication $authentication
     */
    public function __construct(Authentication $authentication)
    {
        $this->authentication = $authentication;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @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);
    }
}
