<?php

namespace App\Http\Middleware;

use App\Models\Company;
use App\Models\DetailUserCompany;
use App\Traits\HasResponse;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;

class JwtMiddleware
{
    use HasResponse;

    public function handle(Request $request, Closure $next): Response
    {
        try {
            $user = JWTAuth::parseToken()->authenticate();
            if (!!$user) {
                if($user->iduser_type != 1){
                    # Variable global
                    $company = Company::find(JWTAuth::payload()->get('idcompany'));
                    $request->merge(['idcompany' => $company ? $company->id : null]);
                    $request->merge(['rut_company' => $company ? $company->rut : null]);
                    $iddetail_user = DetailUserCompany::find(JWTAuth::payload()->get('iddetail_user'));
                    $request->merge(['iddetail_user' => $iddetail_user ? $iddetail_user->id : null]);
                }
                return $next($request);
            }
        } catch (JWTException $e) {
            if ($e instanceof TokenInvalidException) {
                return $this->errorResponse('Token error: Token es inválido', 401);
            } else if ($e instanceof TokenExpiredException) {
                return $this->errorResponse('Token error: Token expirado', 401);
            } else {
                return $this->errorResponse('Token error: Token de autorización no encontrado', 401);
            }
        }
        return $next($request);
    }
}
