<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

/**
 * Reads the authenticated user's organization_id and binds it into
 * the IoC container so the BelongsToOrganization global scope can
 * automatically isolate all queries to the current tenant.
 *
 * This middleware must run AFTER auth:sanctum so that $request->user()
 * is available.  Add it to the auth:sanctum middleware group in routes.
 */
class SetTenantScope
{
    public function handle(Request $request, Closure $next): mixed
    {
        $user = $request->user();

        if ($user && $user->organization_id) {
            app()->instance('current_organization_id', $user->organization_id);
        }

        return $next($request);
    }
}
