<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use Closure;
use Hyperf\HttpMessage\Exception\UnauthorizedHttpException;
use Hyperf\HttpServer\Annotation\Middleware;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;

use Hypervel\Support\Facades\Auth;
use App\Enums\UserTypes;

class EnsureUserHasRole extends Middleware
{
    /**
     * Process an incoming server request.
     * 
     * @param ServerRequestInterface $request
     * @param Closure $next
     * @param string ...$roles
     * @return ResponseInterface
     */
    public function handle(ServerRequestInterface $request, Closure $next, string...$roles): ResponseInterface
    {
        /** @var \App\Models\User $user */
        $user = Auth::user();

        if (!$user) {
            throw new UnauthorizedHttpException('Unauthorized: Please login.');
        }

        foreach ($roles as $role) {
            if ($user->hasRole($role)) {
                return $next($request);
            }
        }

        throw new UnauthorizedHttpException('Unauthorized: You do not have the required role.');
    }
}