<?php

namespace App\Http\Middleware;

use App\Models\Business;

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

/**
 * Resolves the current tenant (Business) for this request and sets it on
 * Business::setCurrent() so the BelongsToBusiness trait can scope queries.
 *
 * Resolution order:
 *   1. Authenticated user's business_id (most common case)
 *   2. X-Business-Id header (useful for API clients managing multiple businesses,
 *      e.g. an agency dashboard switching between client tenants)
 *
 * Adjust resolution order to match your actual auth/user model shape.
 */
class SetCurrentBusiness
{
    public function handle(Request $request, Closure $next): Response
    {
        $businessId = null;

        if ($request->user()) {
            $businessId = $request->user()->business_id;

            if (empty($businessId)) {
                // Find first business owned by the user
                $ownedBusiness = Business::withoutGlobalScopes()
                    ->where('owner_id', $request->user()->id)
                    ->first();

                if ($ownedBusiness) {
                    $businessId = $ownedBusiness->id;
                    $request->user()->update(['business_id' => $businessId]);
                } else {
                    // Try to fallback to any business in the system
                    $anyBusiness = Business::withoutGlobalScopes()->first();
                    if ($anyBusiness) {
                        $businessId = $anyBusiness->id;
                        $request->user()->update(['business_id' => $businessId]);
                    }
                }
            }
        } elseif ($request->hasHeader('X-Business-Id')) {
            $businessId = (int) $request->header('X-Business-Id');
        }

        if ($businessId) {
            $business = Business::withoutGlobalScopes()->find($businessId);

            if ($business) {
                // If business is inactive, only block tenant-specific paths (invoices, customers, items, etc.)
                // Allow managing business profile, business list, settings etc.
                $isTenantSpecificPath = !$request->is('businesses*') && !$request->is('profile*') && !$request->is('logout*');
                if (!$business->is_active && $isTenantSpecificPath) {
                    abort(403, 'Your business account is inactive. Please contact support or manage your businesses.');
                }

                Business::setCurrent($business);
            }
        }

        return $next($request);
    }
}
