package com.usky.issue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.usky.issue.domain.IssueCloudConfig;
import com.usky.issue.mapper.IssueCloudConfigMapper;
import com.usky.issue.service.CloudAuthService;
import com.usky.issue.service.util.AesGcmCipher;
import com.usky.issue.service.util.CredentialMaskUtil;
import com.usky.issue.service.util.HmacSignUtil;
import com.usky.issue.service.vo.SyncPacket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 云平台认证服务实现
 *
 * @author fyc
 * @date 2026-06-08
 */
@Slf4j
@Service
public class CloudAuthServiceImpl implements CloudAuthService {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Autowired
    private IssueCloudConfigMapper configMapper;
    @Autowired
    private AesGcmCipher aesGcmCipher;

    @Override
    public boolean validateToken(String apiKey, Integer tenantId) {
        if (!StringUtils.hasText(apiKey)) {
            log.warn("[连接测试-认证] apiKey 为空 tenantId={}", tenantId);
            return false;
        }
        if (tenantId == null) {
            log.warn("[连接测试-认证] tenantId 为空");
            return false;
        }
        IssueCloudConfig config = findActiveConfig(tenantId);
        if (config == null) {
            log.warn("[连接测试-认证] 云端无启用配置 tenantId={}", tenantId);
            return false;
        }
        boolean matched = matchCredential(apiKey, config);
        if (!matched) {
            log.warn("[连接测试-认证] apiKey 与云端配置不匹配 tenantId={}, configId={}, apiKey={}",
                    tenantId, config.getId(), maskApiKey(apiKey));
        } else {
            log.info("[连接测试-认证] 通过 tenantId={}, configId={}", tenantId, config.getId());
        }
        return matched;
    }

    @Override
    public boolean validate(String apiKey, String sign, SyncPacket packet) {
        if (!validateToken(apiKey, parseTenantId(packet))) {
            return false;
        }
        if (!StringUtils.hasText(sign) || packet == null) {
            return false;
        }
        try {
            String expected = HmacSignUtil.sign(OBJECT_MAPPER.writeValueAsString(packet), apiKey);
            return expected.equals(sign);
        } catch (Exception e) {
            log.warn("签名校验失败: {}", e.getMessage());
            return false;
        }
    }

    private Integer parseTenantId(SyncPacket packet) {
        if (packet == null || !StringUtils.hasText(packet.getTenantId())) {
            return null;
        }
        try {
            return Integer.valueOf(packet.getTenantId());
        } catch (NumberFormatException ex) {
            return null;
        }
    }

    private IssueCloudConfig findActiveConfig(Integer tenantId) {
        return configMapper.selectOne(new QueryWrapper<IssueCloudConfig>()
                .eq("is_deleted", 0)
                .eq("tenant_id", tenantId)
                .eq("status", 1)
                .orderByDesc("id")
                .last("LIMIT 1"));
    }

    private boolean matchCredential(String apiKey, IssueCloudConfig config) {
        try {
            String decrypted = aesGcmCipher.decrypt(config.getCredentialKey());
            return apiKey.equals(decrypted);
        } catch (Exception e) {
            log.warn("凭证解密失败 tenantId={}", config.getTenantId());
            return false;
        }
    }

    private String maskApiKey(String apiKey) {
        return CredentialMaskUtil.mask(apiKey);
    }
}
