<?php

namespace App\Http\Middleware;

use App\Support\AppMode;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureTenant
{
    public function handle(Request $request, Closure $next): Response
    {
        // Self-hosted script mode is single-tenant; tenancy is a no-op.
        if (AppMode::isSelfHosted()) {
            return $next($request);
        }

        $user = $request->user();

        if (! $user || ! $user->tenant_id) {
            abort(403, 'Tenant not resolved for user.');
        }

        return $next($request);
    }
}
