<?php

namespace App\Http\Middleware;

use App\Models\Tenant;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;

class IdentifyTenant
{
    public function handle(Request $request, Closure $next)
    {
        $businessCode = $request->header('X-Business-Code');

        if (!$businessCode) {
            return response()->json(['error' => 'Missing Business Code Header'], 403);
        }

        $tenant = Tenant::where('business_code', $businessCode)->first();

        if (!$tenant) {
            return response()->json(['error' => 'Business not found'], 404);
        }

        Config::set('app.current_tenant_id', $tenant->uuid);

        Config::set('app.current_tenant_code', $businessCode);
        

        return $next($request);
    }
}
