package com.cico.nest.lcdp.boot.core.infra.service.config;

import cn.hutool.core.util.StrUtil;
import com.cico.nest.lcdp.boot.core.infra.controller.admin.config.vo.ConfigPageReqVO;
import com.cico.nest.lcdp.boot.core.infra.controller.admin.config.vo.ConfigSaveReqVO;
import com.cico.nest.lcdp.boot.core.infra.convert.config.ConfigConvert;
import com.cico.nest.lcdp.boot.core.infra.dal.dataobject.config.ConfigDO;
import com.cico.nest.lcdp.boot.core.infra.dal.mysql.config.ConfigMapper;
import com.cico.nest.lcdp.boot.core.infra.dal.redis.RedisKeyConstants;
import com.cico.nest.lcdp.boot.core.infra.enums.config.ConfigTypeEnum;
import com.cico.nest.lcdp.framework.common.pojo.PageResult;
import com.cico.nest.lcdp.framework.common.util.json.JsonUtils;
import com.google.common.annotations.VisibleForTesting;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

import static com.cico.nest.lcdp.boot.api.infra.enums.ErrorCodeConstants.*;
import static com.cico.nest.lcdp.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 参数配置 Service 实现类
 */
@Service
@Slf4j
@Validated
public class ConfigServiceImpl implements ConfigService {

    @Resource
    private ConfigMapper configMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Long createConfig(ConfigSaveReqVO createReqVO) {
        // 校验参数配置 key 的唯一性
        validateConfigKeyUnique(null, createReqVO.getKey());

        // 插入参数配置
        ConfigDO config = ConfigConvert.INSTANCE.convert(createReqVO);
        config.setType(ConfigTypeEnum.CUSTOM.getType());
        configMapper.insert(config);
        return config.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateConfig(ConfigSaveReqVO updateReqVO) {
        // 校验自己存在
        validateConfigExists(updateReqVO.getId());
        // 校验参数配置 key 的唯一性
        validateConfigKeyUnique(updateReqVO.getId(), updateReqVO.getKey());

        // 更新参数配置
        ConfigDO updateObj = ConfigConvert.INSTANCE.convert(updateReqVO);
        configMapper.updateById(updateObj);
        stringRedisTemplate.delete(RedisKeyConstants.CONFIG_KEY+":"+updateObj.getConfigKey());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteConfig(Long id) {
        // 校验配置存在
        ConfigDO config = validateConfigExists(id);
        // 内置配置，不允许删除
        if (ConfigTypeEnum.SYSTEM.getType().equals(config.getType())) {
            throw exception(CONFIG_CAN_NOT_DELETE_SYSTEM_TYPE);
        }
        // 删除
        configMapper.deleteById(id);
        stringRedisTemplate.delete(RedisKeyConstants.CONFIG_KEY+":"+config.getConfigKey());
    }

    @Override
    public ConfigDO getConfig(Long id) {
        return configMapper.selectById(id);
    }

    @Override
    public ConfigDO getConfigByKey(String key) {
        return configMapper.selectByKey(key);
    }

    @Override
    public PageResult<ConfigDO> getConfigPage(ConfigPageReqVO pageReqVO) {
        return configMapper.selectPage(pageReqVO);
    }

    @Override
    public ConfigDO getConfigCacheByKey(String key) {
        String value = stringRedisTemplate.opsForValue().get(RedisKeyConstants.CONFIG_KEY+":"+key);
        if(StrUtil.isEmpty(value)){
            ConfigDO configDO = Optional.ofNullable(this.getConfigByKey(key)).orElse(new ConfigDO());
            value = JsonUtils.toJsonString(configDO);
            stringRedisTemplate.opsForValue().set(RedisKeyConstants.CONFIG_KEY+":" + key,value,Integer.MAX_VALUE, TimeUnit.SECONDS);
        }
        return JsonUtils.parseObject(value, ConfigDO.class);
    }

    @VisibleForTesting
    public ConfigDO validateConfigExists(Long id) {
        if (id == null) {
            return null;
        }
        ConfigDO config = configMapper.selectById(id);
        if (config == null) {
            throw exception(CONFIG_NOT_EXISTS);
        }
        return config;
    }

    @VisibleForTesting
    public void validateConfigKeyUnique(Long id, String key) {
        ConfigDO config = configMapper.selectByKey(key);
        if (config == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的参数配置
        if (id == null) {
            throw exception(CONFIG_KEY_DUPLICATE);
        }
        if (!config.getId().equals(id)) {
            throw exception(CONFIG_KEY_DUPLICATE);
        }
    }

}
