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

import cn.reghao.tnb.common.web.WebResult;
import cn.reghao.tnb.common.auth.AccountRole;
import cn.reghao.tnb.common.auth.UserContext;
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;

/**
 * 根据 url 前缀检测用户是否拥有相应 ROLE
 *
 * @author reghao
 * @date 2025-07-18 09:18:16
 */
@Slf4j
@Component
public class UserRoleInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String uri = request.getRequestURI();
        String method = request.getMethod();
        /*if (uri.startsWith("/api/content/exam")) {
            if (uri.startsWith("/api/content/exam/subject")
                    || uri.startsWith("/api/content/exam/question")
                    || uri.startsWith("/api/content/exam/paper")) {
                if (!UserContext.getUserRoles().contains(AccountRole.examAdmin.getValue())) {
                    String msg = String.format("current user not grant %s role", AccountRole.examAdmin.getDesc());
                    writeResponse(response, msg);
                    return false;
                }
            }

            if (uri.startsWith("/api/content/exam/eval")
                    && !UserContext.getUserRoles().contains(AccountRole.examUser.getValue())) {
                String msg = String.format("current user not grant %s role", AccountRole.examUser.getDesc());
                writeResponse(response, msg);
                return false;
            }
        }*/
        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 {
    }
}
