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

import cn.novalon.gym.manage.sys.core.domain.Dictionary;
import cn.novalon.gym.manage.sys.core.repository.IDictionaryRepository;
import cn.novalon.gym.manage.db.converter.DictionaryConverter;
import cn.novalon.gym.manage.db.dao.DictionaryDao;
import cn.novalon.gym.manage.db.entity.DictionaryEntity;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * 字典仓储实现类
 * 
 * @author 张翔
 * @date 2026-03-13
 */
@Repository
public class DictionaryRepository implements IDictionaryRepository {

    private final DictionaryDao dictionaryDao;
    private final DictionaryConverter dictionaryConverter;

    public DictionaryRepository(DictionaryDao dictionaryDao, DictionaryConverter dictionaryConverter) {
        this.dictionaryDao = dictionaryDao;
        this.dictionaryConverter = dictionaryConverter;
    }

    @Override
    public Flux<Dictionary> findAll() {
        return dictionaryDao.findByDeletedAtIsNullOrderBySortAsc()
                .map(dictionaryConverter::toDomain);
    }

    @Override
    public Flux<Dictionary> findByDeletedAtIsNullOrderBySortAsc() {
        return dictionaryDao.findByDeletedAtIsNullOrderBySortAsc()
                .map(dictionaryConverter::toDomain);
    }

    @Override
    public Mono<Dictionary> findById(Long id) {
        return dictionaryDao.findById(id)
                .map(dictionaryConverter::toDomain);
    }

    @Override
    public Flux<Dictionary> findByType(String type) {
        return dictionaryDao.findByType(type)
                .map(dictionaryConverter::toDomain);
    }

    @Override
    public Mono<Dictionary> findByTypeAndCode(String type, String code) {
        return dictionaryDao.findByTypeAndCodeAndDeletedAtIsNull(type, code)
                .map(dictionaryConverter::toDomain);
    }

    @Override
    public Mono<Boolean> existsByTypeAndCode(String type, String code) {
        return dictionaryDao.findByTypeAndCodeAndDeletedAtIsNull(type, code)
                .map(entity -> true)
                .defaultIfEmpty(false);
    }

    @Override
    public Mono<Dictionary> save(Dictionary dictionary) {
        DictionaryEntity entity = dictionaryConverter.toEntity(dictionary);
        return dictionaryDao.save(entity)
                .map(dictionaryConverter::toDomain);
    }

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

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