package com.sino.mci.admin.security;

import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.stp.StpUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String path = request.getRequestURI();
        String method = request.getMethod();
        if (path.contains("/api/v1/account/login")
                || ("POST".equals(method) && isExactPath(path, "/api/v1/account/tenant"))
                || ("POST".equals(method) && isExactPath(path, "/api/v1/account/user"))
                || isExactPath(path, "/api/v1/health")
                || ("POST".equals(method) && isExactPath(path, "/api/v1/channel-account/heartbeat"))
                || ("POST".equals(method) && isExactPath(path, "/api/v1/channel-account/event"))) {
            return true;
        }

        try {
            StpUtil.checkLogin();
        } catch (SaTokenException e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        return true;
    }

    private boolean isExactPath(String requestUri, String endpointPath) {
        String contextPath = "/msg-platform";
        return requestUri.equals(endpointPath)
                || requestUri.equals(contextPath + endpointPath)
                || requestUri.endsWith(endpointPath) && requestUri.length() == contextPath.length() + endpointPath.length();
    }
}
