package com.oqpo.api.web.interceptor;

import com.oqpo.api.config.JwtTokenProvider;
import com.oqpo.api.enums.SystemMessageCode;
import com.oqpo.api.exception.UnauthorizedException;
import com.oqpo.api.service.system.JobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class TokenCheckInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    JwtTokenProvider jwtTokenProvider;

    @Autowired
    JobService jobService ;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {

            String connKey = jwtTokenProvider.resolveToken(request);
            if (!jwtTokenProvider.isLogin(connKey)){
                throw new UnauthorizedException(SystemMessageCode.NEED_AUTH.getMessage());
            }
            String userId = jwtTokenProvider.getUserId(connKey) ;
            String authTpCd = jwtTokenProvider.getAuthTpCd(connKey);
            String path = request.getServletPath();
            //if (path != null && !"".equals(path)) {path = path.replaceFirst("/", "");}
/*
            MemberEntity memberEntity = new MemberEntity();
            memberEntity.setUserId(jwtTokenProvider.getUserId(connKey));
            memberEntity.setUserNm(jwtTokenProvider.getUserNm(connKey));
            memberEntity.setSystemAdminYn(jwtTokenProvider.getSystemAdminYn(connKey));
            memberEntity.setSuperAdminYn(jwtTokenProvider.getSuperAdminYn(connKey));


            if (!jobService.saveJob(memberEntity, path)) {
                throw new UnauthorizedException(SystemMessageCode.NOT_AUTH.getMessage());
            }
*/
        }catch(UnauthorizedException e) {
            e.printStackTrace();
            throw new UnauthorizedException(e.getErrorMessage());
        }
        return true;
    }
}
