<?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);

        $dealerId = $request->session()->get('current_dealer_id', $user->dealer_id);

        $dealer = null;
        if ($dealerId) {
            $dealer = Dealer::withTrashed()->select(['id', 'is_active'])->find((int) $dealerId);
            if (!$dealer || ! $dealer->is_active || (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);
    }
}
