package com.ff.annotation;

import com.ff.base.constant.Constants;
import com.ff.config.KeyConfig;
import com.ff.base.utils.sign.Md5Utils;
import com.ff.common.domain.TenantSecretKey;
import com.ff.common.service.ITenantSecretKeyService;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 标题检查方面
 *
 * @author shi
 * @date 2025/02/10
 */
@Aspect
@Component
public class HeaderCheckAspect {

    @Resource
    private ITenantSecretKeyService tenantSecretKeyService;

    @Resource
    private KeyConfig keyUtils;


    // 定义切点: 所有带 @CheckHeader 注解的类中的所有方法
    @Pointcut("@within(CheckHeader)")
    public void checkHeaderPointcut() {
    }


    // 在方法执行前进行处理
    @Before("checkHeaderPointcut()")
    public void beforeMethod() throws Exception {
        // 获取当前请求的 HTTP 请求对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        // 32 位小写 md5(random+key+tenantSecret)
        String sign = request.getHeader(Constants.SIGN);
        Assert.notNull(sign, "签名不能为空");
        // 随机数
        String random = request.getHeader(Constants.RANDOM);
        Assert.notNull(random, "随机数不能为空");
        Assert.isTrue( random.length() == 32, "随机数长度错误");

        //key值
        String key = request.getHeader(Constants.KEY);
        Assert.notNull(key, "key不能为空");


        TenantSecretKey tenantSecretKey = tenantSecretKeyService.selectTenantSecretKeyByTenantKey(key);
        Assert.notNull(tenantSecretKey, "key不存在");

        String keyG = Md5Utils.md5New(random + key + tenantSecretKey.getTenantSecret());
        Assert.isTrue(keyG.equals(sign), "签名错误");
        //保存
        keyUtils.set(tenantSecretKey);
    }
}