<?php

namespace App\Http\Middleware;

use App\Domains\Authorization\Enums\RoleCode;
use Closure;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureAdminAppTenant
{
    /**
     * Ensure the authenticated user is an AdminApp user bound to a tenant.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();

        if (
            ! $user
            || $user->rol_codigo !== RoleCode::AdminApp->value
            || ! $user->tenant_codigo
        ) {
            throw new AuthorizationException;
        }

        return $next($request);
    }
}
