<?php

namespace App\Http\Middleware;

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

class SubcontractorMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        if (!$request->user()) {
            return response()->json(['message' => 'Unauthorized'], 401);
        }
        // Get token scopes
        $scopes = $request->user()->token()->scopes;
        if (in_array('admin', $scopes)) {
            // Handle admin user
            $user = Auth::guard('admin')->user();
            if($user->user_type != config('constants.user_types.subcontractor')){
                return response()->json(['message' => 'Unauthorized' ,'statusCode'=> 403], 403);
            }
            if (!$user || !($user instanceof \App\Models\User)) {
                return response()->json(['message' => 'Unauthorized: Invalid admin user' ,'statusCode'=> 403], 403);
            }
            // Additional admin-specific checks if needed
            Auth::setUser($user);
        } 
        elseif (in_array('api', $scopes)) {
            // Handle employee user
            $user = Auth::guard('api')->user();
            if (!$user || !($user instanceof \App\Models\EmpCompanyDetails)) {
                return response()->json(['message' => 'Unauthorized: Invalid employee user' , 'statusCode'=> 403], 403);
            }
            // Additional employee-specific checks if needed
            Auth::setUser($user);
        }
        else {
            return response()->json(['message' => 'Unauthorized: Invalid scope'], 403);
        }
        return $next($request);
    }
}

