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.SysDictType;
import cn.novalon.gym.manage.sys.core.repository.ISysDictTypeRepository;
import cn.novalon.gym.manage.sys.core.service.ISysDictTypeService;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Service
public class SysDictTypeService implements ISysDictTypeService {

    private final ISysDictTypeRepository repository;
    private final IAuditLogService auditLogService;

    public SysDictTypeService(ISysDictTypeRepository repository, IAuditLogService auditLogService) {
        this.repository = repository;
        this.auditLogService = auditLogService;
    }

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

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

    @Override
    public Mono<SysDictType> findByDictType(String dictType) {
        return repository.findByDictTypeAndDeletedAtIsNull(dictType);
    }

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

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