<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ReferralMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        // Try to authenticate with the referral guard
        $user = Auth::guard('referral')->user();
        
        if (!$user) {
            return response()->json(['message' => 'Unauthorized', 'statusCode' => 401], 401);
        }

        // Get token scopes from the request
        $token = $request->user('referral')->token();
        $scopes = $token ? $token->scopes : [];
        
        // Check if user has referral scope
        if (in_array('referral', $scopes)) {
            if (!($user instanceof \App\Models\User)) {
                return response()->json(['message' => 'Unauthorized: Invalid referral user', 'statusCode' => 403], 403);
            }
            
            // Check if user is actually a referral user (customer or referral partner)
            if (!in_array($user->user_type, [2, 4])) {
                return response()->json(['message' => 'Unauthorized: Not a referral user', 'statusCode' => 403], 403);
            }
            
            return $next($request);
        }

        return response()->json(['message' => 'Unauthorized: Invalid scope', 'statusCode' => 403], 403);
    }
}