package cn.reghao.tnb.message.app.service;

import cn.reghao.jutil.jdk.string.SnowFlake;
import cn.reghao.tnb.auth.api.iface.AccountQuery;
import cn.reghao.tnb.common.auth.AccountRole;
import cn.reghao.tnb.common.util.ConstantId;
import cn.reghao.tnb.message.api.dto.UserMessageDto;
import cn.reghao.tnb.message.app.db.mapper.UserMessageMapper;
import cn.reghao.tnb.message.app.model.po.UserMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author reghao
 * @date 2024-04-18 15:07:14
 */
@Slf4j
@Service
public class UserMessageService {
    @DubboReference(check = false, retries = 0, timeout = 60_000)
    private AccountQuery accountQuery;

    private final UserMessageMapper userMessageMapper;
    private final SnowFlake idGenerator;

    public UserMessageService(UserMessageMapper userMessageMapper) {
        this.userMessageMapper = userMessageMapper;
        this.idGenerator = new SnowFlake(1L, 1L);
    }

    public void addMessage(UserMessageDto userMessageDto) {
        long receiverId = userMessageDto.getReceiver();
        if (receiverId == ConstantId.ANONYMOUS_USER_ID) {
            long adminUserId = accountQuery.getByRole(AccountRole.admin.getValue());
            if (adminUserId == ConstantId.ANONYMOUS_USER_ID) {
                log.error("system not init yet");
                return;
            }

            userMessageDto.setReceiver(adminUserId);
        }

        long messageId = idGenerator.nextId();
        UserMessage userMessage = new UserMessage(messageId, userMessageDto);
        userMessageMapper.save(userMessage);
    }

    public List<UserMessage> getMessages(long userId) {
        List<UserMessage> list =  userMessageMapper.findByUnread(userId);
        return list;
    }

    public int getUnreadCount(long userId) {
        int total =  userMessageMapper.countByUnread(userId);
        return total;
    }

    public UserMessage getUserMessage(long messageId) {
        UserMessage userMessage = userMessageMapper.findByMessageId(messageId);
        userMessageMapper.updateSetRead(messageId);
        return userMessage;
    }
}
