package com.kingdee.eas.custom.integration.apimgt.auth.service;

import com.kingdee.eas.custom.integration.apimgt.ApiRegistryBillInfo;
import com.kingdee.eas.custom.integration.apimgt.OpenPlatformAuthBillInfo;
import com.kingdee.eas.custom.integration.apimgt.auth.model.AuthErrorCode;
import com.kingdee.eas.custom.integration.apimgt.auth.model.AuthResult;
import com.kingdee.eas.hr.ats.lightapp.util.DateTimeUtils;
import com.kingdee.shr.base.syssetting.BaseItemStateEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 密钥认证服务
 */
@Service
public class SecretAuthService {

    private static final Logger logger = LoggerFactory.getLogger(SecretAuthService.class);

    private final BosAuthDao bosAuthDao;

    public SecretAuthService(BosAuthDao bosAuthDao) {
        this.bosAuthDao = bosAuthDao;
    }

    /**
     * 根据接口路径和HTTP方法查找接口
     */
    public ApiRegistryBillInfo findApi(String apiPath, String httpMethod) {
        return bosAuthDao.findApiByPathAndMethod(apiPath, httpMethod);
    }

    /**
     * 认证
     */
    public AuthResult authenticate(String appSecret, ApiRegistryBillInfo api) {
        if (appSecret == null || appSecret.isEmpty()) {
            return AuthResult.failure(AuthErrorCode.SECRET_MISSING);
        }

        OpenPlatformAuthBillInfo platform = bosAuthDao.findByAppSecret(appSecret);
        if (platform == null) {
            logger.warn("密钥无效: secret={}", mask(appSecret));
            return AuthResult.failure(AuthErrorCode.SECRET_INVALID);
        }

        BaseItemStateEnum state = platform.getState();
        if (!BaseItemStateEnum.ENABLE.equals(state)) {
            logger.warn("平台已禁用: platform={}", platform.getPlatform());
            return AuthResult.failure(AuthErrorCode.PLATFORM_DISABLED);
        }
        /**
         * 检查密钥是否过期
         */
        Date expireDate = platform.getExpireDate();
        if (expireDate != null && expireDate.before(DateTimeUtils.truncateDate(new Date()))) {
            logger.warn("密钥已过期: platform={}, expireDate={}", platform.getPlatform(), expireDate);
            return AuthResult.failure(AuthErrorCode.SECRET_EXPIRED);
        }
        /**
         * 检查接口权限
         */
        if (api != null && !bosAuthDao.hasApiPermission(platform, api)) {
            logger.warn("无接口调用权限: platform={}, apiPath={}",
                    platform.getPlatform(), api.getApiPath());
            return AuthResult.failure(AuthErrorCode.PERMISSION_DENIED);
        }

        logger.debug("认证通过: platform={}, apiPath={}",
                platform.getPlatform(), api != null ? api.getApiPath() : "null");
        return AuthResult.success(platform, api);
    }

    private String mask(String secret) {
        if (secret == null || secret.length() <= 4) {
            return "****";
        }
        return secret.substring(0, 2) + "****" + secret.substring(secret.length() - 2);
    }
}
