<?php

namespace App\Http\Middleware;

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

class EnsureScannerTenant
{
    /**
     * Ensure the authenticated user can scan tickets for a tenant.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();

        if (
            ! $user
            || ! $user->tenant_codigo
            || ! $user->hasPermission(PermissionCode::ScanTickets->value)
        ) {
            throw new AuthorizationException;
        }

        return $next($request);
    }
}
