<?php

namespace Modules\VrcPortalApi\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Modules\VrcPortalApi\Entities\VrcStaffToken;

/**
 * Bearer-token auth for the VRC staff PWA. Resolves the ERP user behind the
 * token, sets it as the authenticated user (so $user->can() / Gate work for the
 * rest of the request), and enforces the VRC entitlement + a baseline VRC
 * permission. Runs AFTER vrc-portal.connection.
 */
class StaffApiAuth
{
    public function handle(Request $request, Closure $next)
    {
        $token = (string) ($request->bearerToken() ?? '');
        if ($token === '') {
            return response()->json(['message' => 'Unauthenticated'], 401);
        }

        $user = VrcStaffToken::lookup($token);
        if (! $user) {
            return response()->json(['message' => 'Unauthenticated'], 401);
        }

        auth()->setUser($user);

        // Entitlement gate (immune to the Admin#<biz> Gate::before bypass).
        if (function_exists('module_entitled') && ! module_entitled('Vrc')) {
            return response()->json(['message' => 'The repair-center module is not enabled.'], 403);
        }

        if (! $user->can('vrc.repair_order.view')) {
            return response()->json(['message' => 'You do not have access to the workshop.'], 403);
        }

        $request->attributes->set('vrc_user', $user);

        return $next($request);
    }
}
