<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

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

        // super_admin has no tenant — bypass
        if ($user->isSuperAdmin()) {
            return $next($request);
        }

        if (!$user->tenant_id || !$user->tenant) {
            return response()->json(['error' => 'No tenant associated with this account.'], 403);
        }

        // Bind tenant to the request for downstream use
        $request->merge(['_tenant' => $user->tenant]);
        app()->instance('tenant', $user->tenant);

        return $next($request);
    }
}
