package cn.novalon.manage.notify.core.service.impl;

import cn.novalon.manage.notify.core.domain.SysNotice;
import cn.novalon.manage.notify.core.repository.ISysNoticeRepository;
import cn.novalon.manage.notify.core.service.ISysNoticeService;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;

@Service
public class SysNoticeServiceImpl implements ISysNoticeService {

    private final ISysNoticeRepository noticeRepository;

    public SysNoticeServiceImpl(ISysNoticeRepository noticeRepository) {
        this.noticeRepository = noticeRepository;
    }

    @Override
    public Flux<SysNotice> getAllNotices() {
        return noticeRepository.findByDeletedAtIsNull();
    }

    @Override
    public Mono<SysNotice> getNoticeById(Long id) {
        return noticeRepository.findById(id)
                .filter(notice -> notice.getDeletedAt() == null);
    }

    @Override
    public Flux<SysNotice> getNoticesByStatus(String status) {
        return noticeRepository.findByStatusAndDeletedAtIsNull(status);
    }

    @Override
    public Mono<SysNotice> createNotice(SysNotice notice) {
        notice.setCreatedAt(LocalDateTime.now());
        return noticeRepository.save(notice);
    }

    @Override
    public Mono<SysNotice> updateNotice(Long id, SysNotice notice) {
        return noticeRepository.findById(id)
                .flatMap(existingNotice -> {
                    if (notice.getNoticeTitle() != null) {
                        existingNotice.setNoticeTitle(notice.getNoticeTitle());
                    }
                    if (notice.getNoticeContent() != null) {
                        existingNotice.setNoticeContent(notice.getNoticeContent());
                    }
                    if (notice.getStatus() != null) {
                        existingNotice.setStatus(notice.getStatus());
                    }
                    if (notice.getNoticeType() != null) {
                        existingNotice.setNoticeType(notice.getNoticeType());
                    }
                    existingNotice.setUpdatedAt(LocalDateTime.now());
                    return noticeRepository.save(existingNotice);
                });
    }

    @Override
    public Mono<Void> deleteNotice(Long id) {
        return noticeRepository.findById(id)
                .filter(notice -> notice.getDeletedAt() == null)
                .flatMap(notice -> {
                    notice.setDeletedAt(LocalDateTime.now());
                    return noticeRepository.save(notice);
                })
                .then();
    }
}