package com.izouma.zhirongip.service;

import com.izouma.zhirongip.domain.Information;
import com.izouma.zhirongip.domain.Message;
import com.izouma.zhirongip.dto.PageQuery;
import com.izouma.zhirongip.exception.BusinessException;
import com.izouma.zhirongip.repo.InformationRepo;
import com.izouma.zhirongip.repo.MessageRepo;
import com.izouma.zhirongip.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

@Service
@AllArgsConstructor
public class MessageService {

    private final MessageRepo     messageRepo;
    private final InformationRepo informationRepo;

    public Page<Message> all(PageQuery pageQuery) {
        return messageRepo.findAll(JpaUtils.toSpecification(pageQuery, Message.class), JpaUtils.toPageRequest(pageQuery));
    }

    public Message reply(Long id, String content) {
        Message message = messageRepo.findById(id).orElseThrow(new BusinessException("无记录"));
        message.setReply(true);
        message.setReplyContent(content);
        message = messageRepo.save(message);

        informationRepo.save(Information
                .builder()
                .receiveUserId(message.getUserId())
                .isRead(false)
                .messageId(id)
                .content("收到关于提问" + message.getTitle() + "的内容回复：" + message.getReplyContent())
                .build());

        return message;
    }
}
