<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Laravel\Sanctum\PersonalAccessToken;
use Illuminate\Support\Facades\Auth;
class RoleMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next,$role): Response
    {
        
        $user = Auth::user();
        
        // Get token from the request
        $token = $request->bearerToken();
        
        if ($token) {
            $accessToken = PersonalAccessToken::findToken($token);
          
            if ($accessToken && $accessToken->expires_at && now()->gt($accessToken->expires_at)) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Token expired, please log in again.'
                ], 401); 
            }
        }
    
        
        if ($role === 'user' && $user->user_role === 'Prayer Warrior') {
            return $next($request);
        }
        
        if ($role === 'leader' && in_array($user->user_role, ['Pastor', 'Prayer (Leader)', 'Senior Prayer Warrior (Leader)'])) {
            return $next($request);
        }

        return response()->json([
            'message' => 'Unauthorized access: Insufficient role permissions.',
            'user_role' => $user->user_role
        ], 403);
    }
}
