package cn.aqroid.business.auth.interceptor;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.alibaba.fastjson2.JSON;

import cn.aqroid.business.auth.domain.ApiLoginUser;
import cn.aqroid.business.auth.service.ApiTokenService;
import cn.aqroid.business.auth.util.ApiLoginUserHolder;
import cn.aqroid.common.core.tenant.TenantContext;
import cn.aqroid.common.utils.StringUtils;

/**
 * API认证拦截器
 * 用于小程序端接口的Token验证
 *
 * @author aqroid
 * @date 2026-01-12
 */
@Component
public class ApiAuthInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(ApiAuthInterceptor.class);

    @Autowired
    private ApiTokenService apiTokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取Token
        String token = request.getHeader("Authorization");
        
        if (StringUtils.isEmpty(token)) {
            log.debug("请求未携带Token: {}", request.getRequestURI());
            writeUnauthorized(response, "未登录，请先登录");
            return false;
        }

        // 去除Bearer前缀
        token = apiTokenService.getTokenFromHeader(token);

        // 验证Token
        ApiLoginUser loginUser = apiTokenService.validateToken(token);
        
        if (loginUser == null) {
            log.debug("Token验证失败: {}", request.getRequestURI());
            writeUnauthorized(response, "登录已过期，请重新登录");
            return false;
        }

        // 设置当前登录用户
        ApiLoginUserHolder.setLoginUser(loginUser);

        // 如果用户有租户ID，设置到租户上下文
        if (loginUser.getTenantId() != null) {
            TenantContext.setTenantId(loginUser.getTenantId());
        }

        log.debug("API认证通过: userId={}, userType={}, uri={}", 
                loginUser.getUserId(), loginUser.getUserType(), request.getRequestURI());

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 清理上下文
        ApiLoginUserHolder.clear();
        TenantContext.clear();
    }

    /**
     * 写入未授权响应
     */
    private void writeUnauthorized(HttpServletResponse response, String message) throws IOException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 401);
        result.put("msg", message);
        
        response.getWriter().write(JSON.toJSONString(result));
    }
}
