<?php

namespace App\Http\Middleware;

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

/**
 * Enforces server-side: disabled users (users.is_disabled = 1) cannot access any authenticated route.
 * Applied after auth; logs out, invalidates session, redirects to login with message.
 */
class EnsureUserIsActive
{
    public function handle(Request $request, Closure $next)
    {
        $user = $request->user();

        if ($user && ($user->is_disabled || (method_exists($user, 'trashed') && $user->trashed()))) {
            Auth::logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();

            return redirect($this->dealerLoginRoute($request, $user))
                ->withErrors(['email' => 'Your account is not active. Please contact support.']);
        }

        return $next($request);
    }

    private function dealerLoginRoute(Request $request, ?User $user = null): string
    {
        $codeFromRoute = $request->route('code');
        if (is_string($codeFromRoute) && $codeFromRoute !== '') {
            return route('dealer.login.show', ['code' => $codeFromRoute]);
        }

        if ($user && $user->dealer_id) {
            $dealerCode = Dealer::query()
                ->where('id', $user->dealer_id)
                ->value('code');

            if (is_string($dealerCode) && $dealerCode !== '') {
                return route('dealer.login.show', ['code' => $dealerCode]);
            }
        }

        return route('login');
    }
}

