<?php

declare(strict_types=1);

namespace ImovelZapAi\SuperAdmin\Infrastructure\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use ImovelZapAi\SuperAdmin\Domain\Enums\PlatformOperatorRole;
use ImovelZapAi\SuperAdmin\Infrastructure\Persistence\Eloquent\PlatformOperatorModel;
use Symfony\Component\HttpFoundation\Response;

final class EnsurePlatformRole
{
    public function handle(Request $request, Closure $next, string ...$roles): Response
    {
        /** @var PlatformOperatorModel|null $operator */
        $operator = Auth::guard('platform')->user();
        if ($operator === null) {
            abort(401);
        }

        $current = $operator->roleEnum()->value;
        if ($roles !== [] && ! in_array($current, $roles, true) && $current !== PlatformOperatorRole::SuperAdmin->value) {
            abort(403, 'Sem permissão para esta área da plataforma.');
        }

        return $next($request);
    }
}
