<?php

namespace Modules\Bms\Http\Middleware;

use App\Contact;
use App\User;
use Closure;
use Illuminate\Http\Request;
use Modules\Bms\Entities\BmsApiToken;

/**
 * Custom bearer-token auth for the BMS PWAs (no Sanctum — mirrors PortalApi).
 *
 * Usage: ->middleware('bms.api:client') or ->middleware('bms.api:employee').
 * On success attaches to the request:
 *   bms_token       (BmsApiToken)
 *   bms_owner       (App\Contact for client, App\User for employee)
 *   bms_business_id (int)
 */
class BmsApiAuth
{
    public function handle(Request $request, Closure $next, string $guard = 'client')
    {
        $token = $request->bearerToken() ?? '';
        if ($token === '') {
            return response()->json(['message' => 'Unauthenticated'], 401);
        }

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

        $owner = $guard === 'employee'
            ? User::find($row->owner_id)
            : Contact::find($row->owner_id);

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

        $row->forceFill(['last_used_at' => now()])->saveQuietly();

        $request->attributes->set('bms_token', $row);
        $request->attributes->set('bms_owner', $owner);
        $request->attributes->set('bms_business_id', $row->business_id);

        return $next($request);
    }
}
