package cn.reghao.tnb.file.app.config.web;

import cn.reghao.jutil.jdk.http.HeaderNames;
import cn.reghao.tnb.common.web.ServletUtil;
import cn.reghao.tnb.common.auth.LoginUser;
import cn.reghao.tnb.common.auth.UserContext;
import cn.reghao.tnb.common.web.WebResult;
import cn.reghao.tnb.file.app.zoss.service.UserKeyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

/**
 * oss-sdk 请求访问拦截器
 *
 * @author reghao
 * @date 2025-10-20 17:09:07
 */
@Slf4j
@Component
public class OssSdkInterceptor implements HandlerInterceptor {
    private final UserKeyService userKeyService;

    public OssSdkInterceptor(UserKeyService userKeyService) {
        this.userKeyService = userKeyService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String requestId = UUID.randomUUID().toString().replace("-", "");
        request.setAttribute(HeaderNames.XRequestId, requestId);
        long startTime = System.currentTimeMillis();
        request.setAttribute(HeaderNames.XRequestTime, startTime);

        String uri = request.getRequestURI();
        String method = request.getMethod();
        if (uri.startsWith("/api/oss/sdk/")) {
            if (uri.equals("/api/oss/sdk/key/auth")) {
                return true;
            }

            String token = ServletUtil.getBearerToken();
            if (token == null || token.isBlank()) {
                log.error("request {} start with /bg/api/oss/, but not auth", uri);
                response.setStatus(403);
                return false;
            }

            LoginUser loginUser = userKeyService.getUserFromToken(token);
            if (loginUser == null) {
                log.error("request {} start with /api/oss/sdk, but not auth", uri);
                response.setStatus(403);
                return false;
            }
            UserContext user = new UserContext(loginUser);
        }
        return true;
    }

    private void writeResponse(HttpServletResponse response, String msg) throws IOException {
        String retJson = WebResult.failWithMsg(msg);
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        printWriter.write(retJson);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, @Nullable Exception ex) throws Exception {
    }
}
