<?php

namespace App\Http\Middleware;

use App\Models\Tenant;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Resolves the current tenant from the authenticated user and binds it
 * into the IoC container so that TenantScope can use it automatically.
 *
 * Must run AFTER auth:sanctum middleware.
 */
class SetTenantContext
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();

        if ($user && $user->tenant_id) {
            $tenant = Tenant::find($user->tenant_id);

            if ($tenant && $tenant->is_active) {
                // Bind into the container — TenantScope reads this
                app()->instance('current_tenant_id', $tenant->id);
                app()->instance('current_tenant', $tenant);
            }
        }

        return $next($request);
    }
}
