package com.dora.service.impl;

import com.dora.entity.SystemConfig;
import com.dora.mapper.SystemConfigMapper;
import com.dora.service.SystemConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@RequiredArgsConstructor
public class SystemConfigServiceImpl implements SystemConfigService {

    private final SystemConfigMapper systemConfigMapper;

    @Override
    @Cacheable(value = "systemConfigs", key = "#key")
    public int getIntValue(String key, int defaultValue) {
        log.debug("从数据库加载系统配置: {}", key);
        try {
            SystemConfig config = systemConfigMapper.findByKey(key);
            if (config != null) {
                return Integer.parseInt(config.getConfigValue());
            }
        } catch (Exception e) {
            log.error("解析系统配置失败: key={}, 默认值将被使用。", key, e);
        }
        return defaultValue;
    }

    @Override
    @Cacheable(value = "systemConfigs", key = "#key")
    public String getStringValue(String key, String defaultValue) {
        log.debug("从数据库加载系统配置: {}", key);
        SystemConfig config = systemConfigMapper.findByKey(key);
        return (config != null && config.getConfigValue() != null) ? config.getConfigValue() : defaultValue;
    }

    @Override
    @CacheEvict(value = "systemConfigs", allEntries = true)
    public void clearCache() {
        log.info("所有系统配置缓存已被清理。");
    }
}
