<?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;

/**
 * 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) {
            return response()->json([
                'error' => $exception->getMessage(),
            ], 401);
        } catch (Exception $exception) {
            return response()->json([
                'error' => $exception->getMessage(),
            ], 500);
        }

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

        return $next($request);
    }
}
