<?php

namespace Modules\VrcPortalApi\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Modules\Vrc\Entities\VrcPortalOwnerToken;

/**
 * Bearer-token auth for the VRC owner PWA. Runs AFTER vrc-portal.connection so
 * the token lookup hits the VRC project DB. Sets the resolved owner on the
 * request for controllers to read.
 */
class OwnerApiAuth
{
    public function handle(Request $request, Closure $next)
    {
        $token = (string) ($request->bearerToken() ?? '');
        if ($token === '') {
            return response()->json(['message' => 'Unauthenticated'], 401);
        }

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

        $request->attributes->set('vrc_owner', $owner);

        return $next($request);
    }
}
