<?php

namespace App\Http\Middleware;

use App\Models\Dealer;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

/**
 * Enforces server-side: no user under an inactive dealer (dealers.is_active = 0) can access the app.
 * Only runs on routes that use this middleware (authenticated app routes). Never blocks login/public routes.
 *
 * Manual verification: (1) Set dealer is_active=0 -> user logged out, redirect to dealer.inactive.
 * (2) Login with active dealer -> dashboard loads. (3) /login when logged out -> loads (no crash).
 */
class EnsureDealerIsActive
{
    public function handle(Request $request, Closure $next)
    {
        // Never block unauthenticated routes (login, password reset, etc.)
        if (!$request->user()) {
            return $next($request);
        }

        // Resolve dealer id safely: session (if app supports switching) or user->dealer_id
        $dealerId = $request->session()->get('current_dealer_id') ?: $request->user()->dealer_id;

        // If still missing, allow through to avoid lockouts (e.g. System Admin with no dealer)
        if (!$dealerId) {
            return $next($request);
        }

        $dealer = Dealer::withTrashed()->select(['id', 'is_active'])->find($dealerId);

        // If dealer missing or soft deleted or inactive, block access
        if (! $dealer || ! $dealer->is_active || (method_exists($dealer, 'trashed') && $dealer->trashed())) {
            Auth::logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();

            return redirect()->route('dealer.inactive');
        }

        return $next($request);
    }
}
