package com.xindazhou.framework.security.core.rpc;

import com.xindazhou.framework.security.core.LoginUser;
import com.xindazhou.framework.security.core.jwt.ServiceJwtUtil;
import com.xindazhou.framework.security.core.util.SecurityFrameworkUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;

/**
 * 服务间调用的 JWT RequestInterceptor 实现类
 * Feign 请求时，生成 JWT Token 并设置到 header 中
 *
 * @author xindazhou
 */
@Slf4j
public class ServiceJwtRequestInterceptor implements RequestInterceptor {

    private static final String SERVICE_JWT_HEADER = "X-Service-JWT";

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 获取当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        
        if (loginUser == null) {
            // 系统调用场景，没有登录用户，生成系统 Token
            String jwt = ServiceJwtUtil.generateToken(null, null, null, null);
            if (jwt != null) {
                requestTemplate.header(SERVICE_JWT_HEADER, jwt);
                log.info("[ServiceJwtRequestInterceptor] 生成系统 JWT Token: {}", requestTemplate.url());
            } else {
                log.warn("[ServiceJwtRequestInterceptor] 无法生成 JWT Token，URL: {}", requestTemplate.url());
            }
            return;
        }

        try {
            // 生成包含用户信息的 JWT Token
            String jwt = ServiceJwtUtil.generateToken(
                    loginUser.getId(),
                    loginUser.getUserType(),
                    loginUser.getTenantId(),
                    loginUser.getScopes() != null ? String.join(",", loginUser.getScopes()) : null
            );
            
            if (jwt != null) {
                requestTemplate.header(SERVICE_JWT_HEADER, jwt);
                log.info("[ServiceJwtRequestInterceptor] 生成用户 JWT Token: userId={}, URL={}", 
                        loginUser.getId(), requestTemplate.url());
            } else {
                log.warn("[ServiceJwtRequestInterceptor] 无法生成 JWT Token，userId={}, URL={}", 
                        loginUser.getId(), requestTemplate.url());
            }
        } catch (Exception ex) {
            log.error("[ServiceJwtRequestInterceptor] 生成 JWT Token 发生异常，userId={}", loginUser.getId(), ex);
            throw ex;
        }
    }

}

