<?php

namespace App\Http\Middleware;

use App\Support\Authorization\PermissionCatalog;
use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class InitializePermissionsTeam
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();

        if (!$user) {
            setPermissionsTeamId(PermissionCatalog::GLOBAL_TEAM_ID);

            return $next($request);
        }

        $teamId = in_array($user->role, [User::ROLE_CLIENT, User::ROLE_OWNER_STAFF], true)
            ? ((int) ($user->organization_id ?? 0))
            : PermissionCatalog::GLOBAL_TEAM_ID;

        setPermissionsTeamId($teamId);

        return $next($request);
    }
}
