<?php

namespace App\Http\Middleware;

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

/**
 * Enforces server-side: users must have an active branch to access authenticated routes.
 * If a user's branch is missing or inactive, logs them out and redirects to login.
 */
class EnsureUserBranchIsActive
{
    public function handle(Request $request, Closure $next)
    {
        $user = $request->user();

        // Only apply to authenticated users.
        if (! $user) {
            return $next($request);
        }

        if (! $user->branch_id) {
            Auth::logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();

            return redirect($this->dealerLoginRoute($request, $user))
                ->withErrors(['email' => 'Your account is not currently allowed to sign in. Please contact your administrator.']);
        }

        $branch = Branch::withoutGlobalScopes()
            ->select(['id', 'is_active'])
            ->find($user->branch_id);

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

            return redirect($this->dealerLoginRoute($request, $user))
                ->withErrors(['email' => 'Your branch is inactive. Please contact your administrator.']);
        }

        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');
    }
}

