<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Models\Tenant;
use Illuminate\Support\Facades\App;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class IdentifyTenant
{
    public function handle(Request $request, Closure $next)
    {
        $excludedRoutes = [
            'tenants/register',
            'login',
            'register',
            'password/*',
            'patient/*',  // Exclude all patient routes
            'api/patient/*',  // Exclude all API patient routes
            'patient-demo',
            'patient-test',
            'create-demo-patient-flow',
        ];

        foreach ($excludedRoutes as $route) {
            if ($request->is($route)) {
                return $next($request);
            }
        }

        // لا تحاول الوصول إلى tenant إذا لم يكن المستخدم مسجلاً
        if (!auth()->check()) {
            return $next($request);
        }

        $tenant = auth()->user()->tenant;

        if (!$tenant) {
            abort(403, 'No tenant assigned.');
        }

        App::instance('currentTenant', $tenant);

        return $next($request);
    }
}
