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

import com.red.circle.other.app.dto.cmd.user.relation.cp.CpApplyStatusQueryCmd;
import com.red.circle.other.infra.database.rds.entity.user.user.CpApply;
import com.red.circle.other.infra.database.rds.service.user.user.CpApplyService;
import com.red.circle.other.infra.enums.user.user.CpApplyStatus;
import java.time.LocalDateTime;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * CP apply status query.
 */
@Component
@RequiredArgsConstructor
public class CpApplyStatusQryExe {

  private static final long APPLY_WAIT_EXPIRE_HOURS = 24L;

  private final CpApplyService cpApplyService;

  public String execute(CpApplyStatusQueryCmd cmd) {
    CpApply cpApply = cpApplyService.getById(cmd.getApplyId());
    if (Objects.isNull(cpApply)) {
      return null;
    }
    if (isOverdueWait(cpApply)) {
      return CpApplyStatus.EXPIRE.name();
    }
    return cpApply.getStatus();
  }

  private boolean isOverdueWait(CpApply cpApply) {
    return Objects.equals(cpApply.getStatus(), CpApplyStatus.WAIT.name())
        && Objects.nonNull(cpApply.getCreateTime())
        && cpApply.getCreateTime().toLocalDateTime()
            .isBefore(LocalDateTime.now().minusHours(APPLY_WAIT_EXPIRE_HOURS));
  }
}
