<?php

namespace Modules\ClinicStaffPortal\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Modules\ClinicStaffPortal\Entities\CsStaffToken;

/**
 * Bearer-token auth for the staff/doctor PWA API.
 *
 * Looks up the token in clinic_staff_tokens, resolves the ERP user, and logs them
 * in for the rest of the request so the usual $user->can(...) permission checks
 * and business scoping behave exactly like they do in the web app.
 *
 * Also gates on clinic.access_module — the staff app surfaces clinic data,
 * so a user with no clinic access can't get in even with a valid token.
 *
 * Dev escape hatch: tokens prefixed 'demo-' are accepted ONLY when APP_DEBUG=true
 * (lets the PWA's design preview boot without a real login).
 */
class StaffAuth
{
    public function handle(Request $request, Closure $next)
    {
        $token = $request->bearerToken() ?? '';
        if ($token === '') {
            return response()->json(['message' => 'Unauthenticated'], 401);
        }

        if (config('app.debug') && str_starts_with($token, 'demo-')) {
            return $next($request);
        }

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

        // Status guard — a disabled user must not keep a working token.
        if (isset($user->status) && $user->status !== 'active') {
            return response()->json(['message' => 'This account is no longer active.'], 401);
        }

        // Log the user in for this request (stateless) so can()/business scope work.
        auth()->setUser($user);

        // Per-business module entitlement (DB-driven, admin-bypass-immune).
        if (! module_entitled('ClinicStaffPortal')) {
            return response()->json(['message' => 'This module is not enabled for your business.'], 403);
        }

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

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

        return $next($request);
    }
}
