package com.samsung.interceptor;

import com.samsung.core.exception.TokenRetentionTimeoutException;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Log4j2
public class TimeoutCheckInterceptor implements HandlerInterceptor {

    @Value("${security.access.limit.timeout:30}")
    private int limitTimeout;

    static final long MILLISECONDS_PER_MINUTE = 60L*1000L;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        String lastAccessTimeHeader = request.getHeader("last-access-time");
        String impersonate = request.getHeader("original-user-id");
        if(StringUtils.isNotEmpty(lastAccessTimeHeader) && !StringUtils.equals("undefined", lastAccessTimeHeader) && !StringUtils.equals("NaN", lastAccessTimeHeader) && StringUtils.isEmpty(impersonate)){
            long lastActivityTime = Long.parseLong(lastAccessTimeHeader);
            long currentTime = System.currentTimeMillis();
            long jwtRetentionTime = currentTime - lastActivityTime;
            if (jwtRetentionTime > (limitTimeout * MILLISECONDS_PER_MINUTE)) {
                //limitTimeout 동안 사용하지 않으면 자동 로그아웃
                throw new TokenRetentionTimeoutException("Token Retention Timeout");
            }
        }
        return true;
    }
}
