<?php
namespace Root\Core\Middleware;

use Closure;
use Illuminate\Http\Request;
use Root\Core\Helper\InternalApi;
use Illuminate\Support\Facades\Auth;

class RequireUser
{

    public function handle(Request $request, Closure $next)
    {

        if (CoreConfig('app.type') === 'microservices') {

            if(CoreConfig('app.testMode') && !empty($testToken = CoreConfig('app.testToken')))
                $token = $testToken;
            else
                $token = $request->bearerToken();


            if ($token) {
                
                $api = new InternalApi();
                $response = 
                    $api->get()
                        ->to(CoreConfig('user.check.path'))
                        ->withSubDomain(CoreConfig('user.check.subDomain'))
                        ->withHeader([
                            'Authorization' => 'Bearer ' . $token
                        ])
                    ->send()
                ;
        
                if ($api->isSuccess()) {
                    $userData = $api->getResponse();
                    if (!empty($userData)) {
                        $userClass = CoreConfig('user.userModelNameSpace', \App\Models\User::class);
                        $userModel = new $userClass();
                        $userModel->forceFill($userData);
                        Auth::setUser($userModel);
                    }
                }else{
                    return response()->json(['message' => 'Unauthorized'], 401);
                }

            }else{
                return response()->json(['message' => 'Unauthorized'], 401);
            }
        
            return $next($request);

        } else {

            if (CoreConfig('app.getSessionType') === 'api') {

                if (CoreConfig('app.testMode') && !empty($testToken = CoreConfig('app.testToken'))) 
                    $token = $testToken;
                else 
                    $token = $request->bearerToken();
                
                if (empty($token)) 
                    return response()->json(['message' => 'Unauthorized'], 401);
                
                $request->headers->set('Authorization', 'Bearer ' . $token);

                if (!auth('sanctum')->check()) 
                    return response()->json(['message' => 'Unauthorized'], 401);
                
                $user = auth('sanctum')->user();

                Auth::setUser($user);

                $request->setUserResolver(function () use ($user) {
                    return $user;
                });
            }


            if (!Auth::check()) {
                return response()->json(['message' => 'Unauthorized'], 401);
            }

            return $next($request);
        }
    }
    
}