package com.reading.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.reading.platform.entity.SystemSetting;
import com.reading.platform.mapper.SystemSettingMapper;
import com.reading.platform.service.SystemSettingService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统设置服务实现类
 */
@Service
@RequiredArgsConstructor
public class SystemSettingServiceImpl implements SystemSettingService {

    private final SystemSettingMapper systemSettingMapper;

    @Override
    public Map<String, String> getSettings(String tenantId) {
        LambdaQueryWrapper<SystemSetting> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SystemSetting::getTenantId, tenantId);
        List<SystemSetting> settings = systemSettingMapper.selectList(wrapper);
        Map<String, String> result = new HashMap<>();
        for (SystemSetting s : settings) {
            result.put(s.getSettingKey(), s.getSettingValue());
        }
        return result;
    }

    @Override
    public void updateSettings(String tenantId, Map<String, String> settings) {
        for (Map.Entry<String, String> entry : settings.entrySet()) {
            LambdaQueryWrapper<SystemSetting> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SystemSetting::getTenantId, tenantId)
                   .eq(SystemSetting::getSettingKey, entry.getKey());
            SystemSetting existing = systemSettingMapper.selectOne(wrapper);
            if (existing != null) {
                LambdaUpdateWrapper<SystemSetting> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(SystemSetting::getTenantId, tenantId)
                             .eq(SystemSetting::getSettingKey, entry.getKey());
                SystemSetting update = new SystemSetting();
                update.setSettingValue(entry.getValue());
                systemSettingMapper.update(update, updateWrapper);
            } else {
                SystemSetting newSetting = new SystemSetting();
                newSetting.setTenantId(tenantId);
                newSetting.setSettingKey(entry.getKey());
                newSetting.setSettingValue(entry.getValue());
                systemSettingMapper.insert(newSetting);
            }
        }
    }

    @Override
    public String getSetting(String tenantId, String key) {
        LambdaQueryWrapper<SystemSetting> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SystemSetting::getTenantId, tenantId)
               .eq(SystemSetting::getSettingKey, key);
        SystemSetting setting = systemSettingMapper.selectOne(wrapper);
        return setting != null ? setting.getSettingValue() : null;
    }
}
