<?php

namespace App\Http\Middleware;

use App\Models\Dealer;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class RequireDefaultDealer
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();
        if (!$user) {
            abort(403);
        }

        // Resolve current dealer id in the same way as other dealer-scoped middleware.
        $dealerId = $request->session()->get('current_dealer_id') ?: $user->dealer_id;

        if (!$dealerId) {
            abort(403);
        }

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

        if (! $dealer || ! $dealer->is_default) {
            if ($request->expectsJson()) {
                abort(403, 'Only the default dealer can access dealer management.');
            }

            return redirect()
                ->route('dashboard.index')
                ->withErrors(['dealer' => 'Only the default dealer can access dealer management.']);
        }

        return $next($request);
    }
}

