package com.chinaweal.aiccs.org.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinaweal.aiccs.common.constant.CommonConstants;
import com.chinaweal.aiccs.org.entity.OauthClient;
import com.chinaweal.aiccs.org.mapper.OauthClientMapper;
import com.chinaweal.aiccs.org.service.IOauthClientService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * OAuth登录的客户端登记信息 服务实现类
 * </p>
 *
 * @author chinaweal
 * @since 2025-11-21
 */
@Slf4j
@Service
public class OauthClientServiceImpl extends ServiceImpl<OauthClientMapper, OauthClient> implements IOauthClientService {

    @Override
    public OauthClient getByClientId(String clientId) {
        if (!StringUtils.hasText(clientId)) {
            return null;
        }
        return lambdaQuery().eq(OauthClient::getClientId, clientId).eq(OauthClient::getIsActive, CommonConstants.TRUE_1).one();
    }

    @Override
    public boolean validateClient(String clientId, String clientSecret) {
        if (!StringUtils.hasText(clientId) || !StringUtils.hasText(clientSecret)) {
            log.warn("客户端ID或秘钥为空，验证失败");
            return false;
        }

        OauthClient client = getByClientId(clientId);
        if (client == null) {
            log.warn("客户端ID不存在: {}", clientId);
            return false;
        }

        boolean isValid = clientSecret.equals(client.getClientSecret());
        if (!isValid) {
            log.warn("客户端秘钥验证失败: {}", clientId);
        }

        return isValid;
    }

}