package com.red.circle.order.app.command.pay.web;

import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.order.app.common.MiFaPayMysqlOrderSupport;
import com.red.circle.order.app.dto.clientobject.pay.PayOrderStatusCO;
import com.red.circle.order.app.dto.cmd.PayOrderStatusCmd;
import com.red.circle.order.infra.database.rds.entity.order.OrderUserPurchasePay;
import com.red.circle.order.infra.database.rds.service.order.OrderUserPurchasePayService;
import com.red.circle.order.inner.asserts.OrderErrorCode;
import com.red.circle.order.inner.model.enums.inapp.InAppPurchaseStatus;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 支付单状态查询.
 *
 * @author system
 */
@Component
@RequiredArgsConstructor
public class PayWebOrderStatusQueryExe {

  private final OrderUserPurchasePayService orderUserPurchasePayService;

  public PayOrderStatusCO execute(PayOrderStatusCmd cmd) {
    OrderUserPurchasePay mysqlOrder = getMysqlOrder(cmd.getOrderId());
    ResponseAssert.notNull(OrderErrorCode.NO_PURCHASE_RECORD_FOUND, mysqlOrder);
    ResponseAssert.isTrue(OrderErrorCode.NO_PURCHASE_RECORD_FOUND,
        Objects.equals(mysqlOrder.getUserId(), cmd.getReqUserId()));
    InAppPurchaseStatus status = MiFaPayMysqlOrderSupport
        .toInAppPurchaseStatus(mysqlOrder.getPayStatus());
    return new PayOrderStatusCO()
        .setOrderId(Objects.toString(mysqlOrder.getId(), null))
        .setTradeNo(mysqlOrder.getFactoryOrderId())
        .setStatus(Objects.toString(status, null))
        .setSuccess(MiFaPayMysqlOrderSupport.isSuccess(mysqlOrder.getPayStatus()))
        .setFinished(MiFaPayMysqlOrderSupport.isFinished(mysqlOrder.getPayStatus()))
        .setReason(mysqlOrder.getReason())
        .setFactoryCode(mysqlOrder.getFactoryCode())
        .setFactoryChannelCode(mysqlOrder.getPaymentChannel())
        .setCurrency(mysqlOrder.getPaymentUnit())
        .setAmount(mysqlOrder.getPaymentAmount())
        .setUpdateTime(mysqlOrder.getUpdateTime());
  }

  private OrderUserPurchasePay getMysqlOrder(String orderId) {
    Long mysqlOrderId = MiFaPayMysqlOrderSupport.parseOrderId(orderId);
    return mysqlOrderId == null ? null : orderUserPurchasePayService.getById(mysqlOrderId);
  }
}
