package net.geedge.common.config;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.log.Log;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.geedge.common.T;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

@Configuration(proxyBeanMethods = false)
public class TokenInterceptor implements WebMvcConfigurer {
    private final static Log log = Log.get();

    private static String tokenValue;

    @Value("${env.tokenFile:config/token.auth}")
    protected String tokenFile;


    @PostConstruct
    public void init() throws IORuntimeException {
        tokenValue = readToken();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                String token = request.getHeader("Authorization");
                if (token == null || !token.equals(tokenValue)) {
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    response.getWriter().write("Unauthorized");
                    return false;
                }
                return true;
            }
        }).addPathPatterns("/**");
    }

    private String readToken() throws IORuntimeException {
        File tf = T.FileUtil.file(T.WebPathUtil.getRootPath(), tokenFile);
        log.info("token file path: {}", tf.getAbsolutePath());
        String token = T.FileUtil.readString(tf, T.CharsetUtil.UTF_8);
        return T.StrUtil.trim(token);
    }
}
