package com.backendsys.modules.sdk.klingai.utils;

import cn.hutool.core.convert.Convert;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.backendsys.modules.common.config.redis.utils.RedisUtil;
import com.backendsys.modules.sdk.klingai.config.KLingConfig;
import com.backendsys.modules.sdk.klingai.entity.KLResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.ClientResponse;
import reactor.core.publisher.Mono;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

@Component
public class KLingUtil {

    @Autowired
    private KLingConfig config;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 接口鉴权：https://docs.qingque.cn/d/home/eZQAyImcbaS0fz-8ANjXvU5ed?identityId=1oEG9JKKMFv#section=h.9mwdken9otn8
     */
    public String sign() {
        try {

            System.out.println("[sign] accessKey: " + config.ACCESS_KEY + ", secretKey: " + config.SECRET_KEY);

            Date expiredAt = new Date(System.currentTimeMillis() + 1800*1000); // 有效时间，此处示例代表当前时间+1800s(30min)
            Date notBefore = new Date(System.currentTimeMillis() - 5*1000); //开始生效的时间，此处示例代表当前时间-5秒
            Algorithm algo = Algorithm.HMAC256(config.SECRET_KEY);
            Map<String, Object> header = new HashMap<>();
            header.put("alg", "HS256");
            return JWT.create()
                .withIssuer(config.ACCESS_KEY)
                .withHeader(header)
                .withExpiresAt(expiredAt)
                .withNotBefore(notBefore)
                .sign(algo);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取接口鉴权Token (增加缓存:10秒)
     */
    public String getToken() {
        String token = "";
        String cacheKey = "klingai:token";
        String cacheValue = redisUtil.getCacheObject(cacheKey);
        if (cacheValue == null) {
            token = sign();
            if (token != null) {
                Integer timeout = Convert.toInt(config.TOKEN_DURATION_TIME);
                redisUtil.setCacheObject(cacheKey, token, timeout, TimeUnit.MILLISECONDS);
            }
        } else {
            token = cacheValue;
        }
        return token;
    }

    /**
     * 获取 Token 拼接好的 HttpHeaders
     */
    public Consumer<HttpHeaders> getHttpHeaders() {
        Consumer<HttpHeaders> httpHeaders = (headers) -> {
            headers.add("Authorization", "Bearer " + getToken());
        };
        return httpHeaders;
    }

    /**
     * 封装错误响应的映射逻辑
     * @param originalResponse 原始的 KLResponse 对象
     * @return 新的 KLResponse 对象，包含统一的错误信息
     */
    public static KLResponse mapErrorResponse(KLResponse originalResponse) {
        // 构建统一错误响应
        KLResponse errorResponse = new KLResponse();
        errorResponse.setCode(originalResponse.getCode());
        errorResponse.setMessage(originalResponse.getMessage());
        errorResponse.setRequest_id(originalResponse.getRequest_id());
        errorResponse.setData(originalResponse.getData());
        return errorResponse;
    }

}
