package com.red.circle.other.app.listener.user;

import com.red.circle.component.mq.MessageEventProcess;
import com.red.circle.component.mq.MessageEventProcessDescribe;
import com.red.circle.component.mq.config.RocketMqMessageListener;
import com.red.circle.component.mq.service.Action;
import com.red.circle.component.mq.service.ConsumerMessage;
import com.red.circle.component.mq.service.MessageListener;
import com.red.circle.mq.business.model.event.user.AccountBeautifulNumberEvent;
import com.red.circle.mq.rocket.business.streams.AccountBeautifulNumberSink;
import com.red.circle.other.infra.database.rds.entity.user.user.UserBeautifulNumber;
import com.red.circle.other.infra.database.rds.service.user.user.UserBeautifulNumberService;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 靓号记录处理.
 *
 * @author pengliang on 2020/12/18
 */
@Slf4j
@RequiredArgsConstructor
@RocketMqMessageListener(groupId = AccountBeautifulNumberSink.INPUT, tag = AccountBeautifulNumberSink.TAG)
public class AccountBeautifulNumberCmdListener implements MessageListener {

  private final MessageEventProcess messageEventProcess;
  private final UserBeautifulNumberService userBeautifulNumberService;

  @Override
  public Action consume(ConsumerMessage message) {
    return messageEventProcess.consume(
        MessageEventProcessDescribe.builder()
            .consumeMsgTimeoutMinute(15)
            .logTag("靓号")
            .repeatConsumeTag("AccountBeautiful")
            .checkConsumeTag(AccountBeautifulNumberSink.TAG)
            .message(message)
            .build(),
        AccountBeautifulNumberEvent.class,
        eventBody -> {
          if (Objects.equals(eventBody.getAccountType(),
              AccountBeautifulNumberEvent.AccountTypeEnum.USER_ACCOUNT)) {
            if (!userBeautifulNumberService.exists(eventBody.getAccount())) {
              userBeautifulNumberService.save(new UserBeautifulNumber()
                  .setUserAccount(eventBody.getAccount())
                  .setType(Objects.toString(eventBody.getPrettyAccountType(), ""))
                  .setStatus(0)
              );
            }
          }
        });
  }

}
