package com.dora.service.impl;

import com.dora.entity.PointsConfig;
import com.dora.entity.SystemConfig;
import com.dora.mapper.PointsConfigMapper;
import com.dora.mapper.SystemConfigMapper;
import com.dora.service.AdminConfigService;
import com.dora.service.SystemConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class AdminConfigServiceImpl implements AdminConfigService {

    private final PointsConfigMapper pointsConfigMapper;
    private final SystemConfigMapper systemConfigMapper;
    private final SystemConfigService systemConfigService;

    // Points Config Management
    @Override
    public List<PointsConfig> getAllPointsConfigs() {
        return pointsConfigMapper.findAll();
    }

    @Override
    public PointsConfig createPointsConfig(PointsConfig pointsConfig) {
        pointsConfigMapper.insert(pointsConfig);
        return pointsConfig;
    }

    @Override
    public PointsConfig updatePointsConfig(Long id, PointsConfig pointsConfig) {
        pointsConfig.setId(id);
        pointsConfigMapper.update(pointsConfig);
        return pointsConfigMapper.findById(id);
    }

    @Override
    public void deletePointsConfig(Long id) {
        pointsConfigMapper.delete(id);
    }

    // System Config Management
    @Override
    public List<SystemConfig> getAllSystemConfigs() {
        return systemConfigMapper.findAll();
    }

    @Override
    public SystemConfig updateSystemConfig(String key, String value) {
        SystemConfig config = systemConfigMapper.findByKey(key);
        if (config != null) {
            config.setConfigValue(value);
            systemConfigMapper.update(config);
            // VERY IMPORTANT: Clear the cache after updating the config
            systemConfigService.clearCache();
            return config;
        }
        // Optionally, throw an exception if the key is not found
        return null;
    }
}
