package cn.novalon.gym.manage.sys.core.service.impl;

import cn.novalon.gym.manage.sys.audit.AuditLogHelper;
import cn.novalon.gym.manage.sys.audit.service.IAuditLogService;
import cn.novalon.gym.manage.sys.core.domain.SysConfig;
import cn.novalon.gym.manage.sys.core.repository.ISysConfigRepository;
import cn.novalon.gym.manage.sys.core.service.ISysConfigService;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Service
public class SysConfigService implements ISysConfigService {

    private final ISysConfigRepository repository;
    private final IAuditLogService auditLogService;

    public SysConfigService(ISysConfigRepository repository, IAuditLogService auditLogService) {
        this.repository = repository;
        this.auditLogService = auditLogService;
    }

    @Override
    public Flux<SysConfig> findAll() {
        return repository.findByDeletedAtIsNull();
    }

    @Override
    public Mono<SysConfig> findById(Long id) {
        return repository.findById(id);
    }

    @Override
    public Mono<SysConfig> findByConfigKey(String configKey) {
        return repository.findByConfigKeyAndDeletedAtIsNull(configKey);
    }

    @Override
    public Mono<SysConfig> save(SysConfig config) {
        return repository.save(config)
                .flatMap(saved -> AuditLogHelper.record(auditLogService, "Config", saved.getId(), "CREATE", saved)
                        .thenReturn(saved));
    }

    @Override
    public Mono<Void> deleteById(Long id) {
        return repository.findById(id)
                .flatMap(config -> repository.deleteByIdAndDeletedAtIsNull(id)
                        .then(AuditLogHelper.record(auditLogService, "Config", id, "DELETE", config, null)))
                .then();
    }

    @Override
    public Mono<String> getConfigValue(String configKey) {
        return findByConfigKey(configKey)
                .map(SysConfig::getConfigValue);
    }
}
