package cn.novalon.gym.manage.db.repository;

import cn.novalon.gym.manage.db.converter.SysConfigConverter;
import cn.novalon.gym.manage.db.dao.SysConfigDao;
import cn.novalon.gym.manage.db.entity.SysConfigEntity;
import cn.novalon.gym.manage.sys.core.domain.SysConfig;
import cn.novalon.gym.manage.sys.core.repository.ISysConfigRepository;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * 系统配置仓储实现类
 * 
 * @author 张翔
 * @date 2026-03-13
 */
@Repository
public class SysConfigRepository implements ISysConfigRepository {

    private final SysConfigDao sysConfigDao;
    private final SysConfigConverter sysConfigConverter;

    public SysConfigRepository(SysConfigDao sysConfigDao, SysConfigConverter sysConfigConverter) {
        this.sysConfigDao = sysConfigDao;
        this.sysConfigConverter = sysConfigConverter;
    }

    @Override
    public Mono<SysConfig> findById(Long id) {
        return sysConfigDao.findById(id)
                .map(sysConfigConverter::toDomain);
    }

    @Override
    public Mono<SysConfig> findByConfigKeyAndDeletedAtIsNull(String configKey) {
        return sysConfigDao.findByConfigKeyAndDeletedAtIsNull(configKey)
                .map(sysConfigConverter::toDomain);
    }

    @Override
    public Flux<SysConfig> findByDeletedAtIsNull() {
        return sysConfigDao.findByDeletedAtIsNull()
                .map(sysConfigConverter::toDomain);
    }

    @Override
    public Flux<SysConfig> findAll() {
        return sysConfigDao.findByDeletedAtIsNull()
                .map(sysConfigConverter::toDomain);
    }

    @Override
    public Flux<SysConfig> findAll(Sort sort) {
        return sysConfigDao.findByDeletedAtIsNull(sort)
                .map(sysConfigConverter::toDomain);
    }

    @Override
    public Mono<SysConfig> save(SysConfig config) {
        SysConfigEntity entity = sysConfigConverter.toEntity(config);
        return sysConfigDao.save(entity)
                .map(sysConfigConverter::toDomain);
    }

    @Override
    public Mono<Void> deleteByIdAndDeletedAtIsNull(Long id) {
        return sysConfigDao.deleteByIdAndDeletedAtIsNull(id);
    }

    @Override
    public Mono<Long> count() {
        return sysConfigDao.countByDeletedAtIsNull();
    }

    @Override
    public Mono<Boolean> existsByConfigKey(String configKey) {
        return sysConfigDao.findByConfigKeyAndDeletedAtIsNull(configKey)
                .map(config -> true)
                .defaultIfEmpty(false);
    }
}