<?php

namespace App\Http\Middleware;

use App\Models\Dealer;
use Closure;
use Illuminate\Http\Request;
use Spatie\Permission\PermissionRegistrar;

/**
 * Sets current dealer context and Spatie team id. Does NOT check dealer is_active
 * (handled by EnsureDealerIsActive middleware after this).
 */
class SetCurrentDealer
{
    public function handle(Request $request, Closure $next)
    {
        $user = $request->user();
        if (!$user) {
            return $next($request);
        }

        $registrar = app(PermissionRegistrar::class);

        // System admins may switch dealers via session; dealer-scoped users must be pinned to their own dealer_id.
        if ($user->hasSystemAdminRole()) {
            $dealerId = $request->session()->get('current_dealer_id', $user->dealer_id);
        } else {
            $dealerId = (int) $user->dealer_id;
        }

        if ($dealerId) {
            $dealer = Dealer::withTrashed()->select(['id'])->find((int) $dealerId);
            if (! $dealer || (method_exists($dealer, 'trashed') && $dealer->trashed())) {
                $dealerId = null;
            } else {
                $dealerId = (int) $dealer->id;
            }
        }

        if ($user->hasSystemAdminRole()) {
            app()->instance('currentDealerId', $dealerId ?: null);
            $registrar->setPermissionsTeamId($dealerId ?: null);
            $registrar->forgetCachedPermissions();

            return $next($request);
        }

        if (empty($dealerId)) {
            return response()->view('errors.no-dealer-assigned', [], 403);
        }

        app()->instance('currentDealerId', $dealerId);

        $registrar->setPermissionsTeamId($dealerId);
        $registrar->forgetCachedPermissions();

        return $next($request);
    }
}
