<?php

namespace App\Http\Middleware;

use App\Services\LocationService;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureWarehouseCatalogueAccess
{
    public function __construct(protected LocationService $locationService)
    {
    }

    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();
        if (!$user) {
            abort(401);
        }

        if (!$this->locationService->currentLocationIsWarehouse($user)) {
            $message = 'Restock and product / category / unit changes are only allowed at a warehouse. Switch location to a warehouse.';

            if ($request->expectsJson()) {
                return response()->json(['error' => $message], 403);
            }

            abort(403, $message);
        }

        return $next($request);
    }
}
