<?php

namespace Modules\PortalApi\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Modules\PortalApi\Entities\PortalOwnerToken;

/**
 * Real bearer-token auth for the pet-owner PWA API.
 *
 * Replaces DemoAuth: looks up the token in portal_owner_tokens,
 * verifies it's not expired, attaches the resolved owner to the
 * request as $request->attributes->get('portal_owner').
 *
 * For backward compatibility with the PWA's dev "Skip to demo" button,
 * tokens prefixed 'demo-' are still accepted ONLY when APP_DEBUG=true.
 */
class PortalAuth
{
    public function handle(Request $request, Closure $next)
    {
        $token = $request->bearerToken() ?? '';
        if ($token === '') {
            return response()->json(['message' => 'Unauthenticated'], 401);
        }

        // Dev escape hatch — lets the PWA's "Skip to demo" keep working
        // during local development without seeding an owner row.
        if (config('app.debug') && str_starts_with($token, 'demo-')) {
            return $next($request);
        }

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

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

        return $next($request);
    }
}
