package com.backendsys.aspect;

import cn.hutool.core.convert.Convert;
import com.backendsys.modules.common.config.security.utils.TokenUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class HttpRequestAspect {

    @Autowired
    private TokenUtil tokenUtil;

    @Pointcut("execution(public * com.backendsys.service.*.*(..))")
    public void serviceMethods() {}

    /**
 *  获取HttpServletRequest 对象
     */
    private HttpServletRequest getRequest() {
        // 获取HttpServletRequest对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes != null ? attributes.getRequest() : null;
        return request;
    }

    /**
     * 从 Token 中获得 user_id
     */
    @Before("serviceMethods()")
    public Long getUserId() {
        HttpServletRequest request = getRequest();
        if (request != null) {
            Claims tokenInfo = tokenUtil.getTokenInfo(request);
            if (tokenInfo != null) {
                return Convert.toLong(tokenInfo.get("user_id"));
            }
        }
        return null;
    }

    /**
     * 从 Token 中获得 member_id
     */
    @Before("serviceMethods()")
    public Long getMemberId() {
        HttpServletRequest request = getRequest();
        if (request != null) {
            Claims tokenInfo = tokenUtil.getTokenInfo(request);
            if (tokenInfo != null) {
                return Convert.toLong(tokenInfo.get("member_id"));
            }
        }
        return null;
    }
}
