<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

/**
 * Middleware to ensure the logged-in user has a linked seller profile.
 * Protects against null pointer errors when accessing Auth::user()->seller->...
 */
class EnsureSellerProfile
{
    public function handle(Request $request, Closure $next): Response
    {
        if (!Auth::check()) {
            return redirect('login');
        }

        $user = Auth::user();

        // Check if user has a seller profile
        if (!$user->seller) {
            // Log this for debugging
            \Illuminate\Support\Facades\Log::warning('User ' . $user->id . ' tried to access seller area without seller profile.');

            return redirect()->route('register.seller.start')
                ->with('error', 'Your seller profile is incomplete. Please complete your registration.');
        }

        return $next($request);
    }
}
