<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Models\LeasingProfile;

class EnsureLeasingProfileExists
{
    /**
     * Handle an incoming request.
     * Ensure every leasing user has a profile record to prevent 500 errors and redirect loops.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();

        if ($user && $user->isLeasing()) {
            if (!$user->leasingProfile) {
                // Auto-create profile if missing
                LeasingProfile::create([
                    'user_id' => $user->id,
                    'company_name' => $user->name,
                ]);
                
                // Refresh the user instance to include the newly created relationship
                $user->load('leasingProfile');
            }
        }

        return $next($request);
    }
}
