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

import com.google.common.collect.Sets;
import com.red.circle.external.inner.endpoint.message.ImMessageClient;
import com.red.circle.other.app.dto.cmd.user.relation.cp.CpApplyDismissCmd;
import com.red.circle.other.infra.common.user.UserGiftBackpackCommon;
import com.red.circle.other.infra.database.cache.service.user.UserCpValueCacheService;
import com.red.circle.other.infra.database.mongo.service.user.count.WeekCpValueCountService;
import com.red.circle.other.infra.database.rds.service.user.user.CpApplyService;
import com.red.circle.other.infra.database.rds.service.user.user.CpBlessRecordService;
import com.red.circle.other.infra.database.rds.service.user.user.CpCabinAchieveService;
import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService;
import com.red.circle.other.infra.database.rds.service.user.user.CpValueService;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 取消CP申请.
 *
 * @author pengliang on 2021/7/14
 */
@Component
@RequiredArgsConstructor
public class DismissCpApplyCmdExe {

  private final CpValueService cpValueService;
  private final CpApplyService cpApplyService;
  private final ImMessageClient imMessageClient;
  private final CpRelationshipService cpRelationshipService;
  private final UserGiftBackpackCommon userGiftBackpackCommon;
  private final WeekCpValueCountService weekCpValueCountService;
  private final UserCpValueCacheService userCpValueCacheService;
  private final CpBlessRecordService cpBlessRecordService;
  private final CpCabinAchieveService cpCabinAchieveService;

  public void execute(CpApplyDismissCmd cmd) {

    var cpRelationship = cpRelationshipService.getByUserId(cmd.requiredReqUserId());
    if (Objects.isNull(cpRelationship)) {
      return;
    }

    cpApplyService.dismiss(cmd.requiredReqUserId());

    cpRelationshipService.deleteCpRelationship(cmd.requiredReqUserId());

    weekCpValueCountService.removeThisWeek(cpRelationship.getUserId(),
        cpRelationship.getCpUserId());

    cpValueService.deleteById(cpRelationship.getCpValId());

    userGiftBackpackCommon.removeUserCpGift(
        Sets.newHashSet(cmd.requiredReqUserId(), cpRelationship.getCpUserId()));

    userCpValueCacheService.remove(cpRelationship.getUserId(), cpRelationship.getCpUserId());

    cpCabinAchieveService.deleteByCpValId(cpRelationship.getCpValId());
    cpBlessRecordService.deleteByCpValId(cpRelationship.getCpValId());

    imMessageClient.sendMessageText(getSendApplyUserId(cmd),
        String.valueOf(cpRelationship.getCpUserId()), cmd.getApplyText());
  }

  private String getSendApplyUserId(CpApplyDismissCmd cmd) {
    return cmd.requiredReqUserId().toString();
  }

}
