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

import com.red.circle.other.app.dto.cmd.user.relation.cp.CpApplyIdQueryCmd;
import com.red.circle.other.infra.database.rds.service.user.user.CpApplyService;
import com.red.circle.other.infra.enums.user.user.CpRelationshipType;
import java.util.Objects;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * cp申请查询.
 *
 * @author pengliang on 2021/7/14
 */
@Component
@RequiredArgsConstructor
public class CpApplyIdQryExe {

  private final CpApplyService cpApplyService;

  public String execute(CpApplyIdQueryCmd cmd) {
    Long currentUserId = cmd.requiredReqUserId();
    Long targetUserId = cmd.getUserId();
    String relationType = CpRelationshipType.normalize(cmd.getRelationType());
    cpApplyService.expireOverdueWaitApplies(currentUserId);
    cpApplyService.expireOverdueWaitApplies(targetUserId);

    Long applyId = cpApplyService.getId(targetUserId, currentUserId, relationType);
    if (isEmptyApplyId(applyId)) {
      applyId = cpApplyService.getId(currentUserId, targetUserId, relationType);
    }
    return Optional.ofNullable(applyId)
        .filter(id -> id > 0)
        .map(String::valueOf)
        .orElse(null);
  }

  private boolean isEmptyApplyId(Long applyId) {
    return Objects.isNull(applyId) || applyId <= 0;
  }

}
