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

import cn.novalon.manage.notify.core.domain.SysUserMessage;
import cn.novalon.manage.notify.core.repository.ISysUserMessageRepository;
import cn.novalon.manage.notify.core.service.ISysUserMessageService;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;

@Service
public class SysUserMessageServiceImpl implements ISysUserMessageService {

    private final ISysUserMessageRepository messageRepository;

    public SysUserMessageServiceImpl(ISysUserMessageRepository messageRepository) {
        this.messageRepository = messageRepository;
    }

    @Override
    public Flux<SysUserMessage> getMessagesByUser(Long userId) {
        return messageRepository.findByUserIdOrderByCreateTimeDesc(userId);
    }

    @Override
    public Mono<Long> getUnreadCount(Long userId) {
        return messageRepository.countByUserIdAndIsRead(userId, "0");
    }

    @Override
    public Flux<SysUserMessage> getUnreadMessages(Long userId) {
        return messageRepository.findByUserIdAndIsReadOrderByCreateTimeDesc(userId, "0");
    }

    @Override
    public Mono<SysUserMessage> createMessage(SysUserMessage message) {
        message.setCreateTime(LocalDateTime.now());
        message.setIsRead("0");
        return messageRepository.save(message);
    }

    @Override
    public Mono<SysUserMessage> markAsRead(Long id) {
        return messageRepository.findById(id)
                .flatMap(message -> {
                    message.setIsRead("1");
                    return messageRepository.save(message);
                });
    }

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