package com.red.circle.order.adapter.app;

import com.red.circle.component.pay.PayProperties;
import com.red.circle.component.pay.clipspay.ClipspayUtils;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.ResponseErrorCode;
import com.red.circle.order.infra.database.mongo.order.InAppPurchaseDetailsService;
import com.red.circle.order.infra.database.mongo.order.entity.InAppPurchaseDetails;
import com.red.circle.order.inner.model.enums.inapp.InAppPurchaseStatus;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author pengliang on 2023/2/14
 */
@Slf4j
@Controller
@RequiredArgsConstructor
@RequestMapping(value = "/clipspay", produces = MediaType.APPLICATION_JSON_VALUE)
public class ClipspayController {

  private final PayProperties payProperties;
  private final InAppPurchaseDetailsService inAppPurchaseDetailsService;

  @RequestMapping("/redirect")
  public void redirect(String respCode, String orderNo, String respDesc, HttpServletResponse resp)
      throws IOException {

    InAppPurchaseDetails details = inAppPurchaseDetailsService.getById(orderNo);
    ResponseAssert.notNull(ResponseErrorCode.REQUEST_PARAMETER_ERROR, details);

    if (!ClipspayUtils.isSuccess(respCode)) {
      inAppPurchaseDetailsService.updateStatusReason(
          details.getId(),
          InAppPurchaseStatus.FAIL,
          respDesc
      );
    }

    String redirectUri = payProperties.getWebPayResultPageUrl()
        + "?redirect=" + payProperties.getWebPayRechargePage()
        + "&appId=" + details.getTrackId()
        + "&appStatus=" + (ClipspayUtils.isSuccess(respCode) ? 0 : 1)
        + "&appType=" + details.getTrackCommodityType();

    resp.sendRedirect(redirectUri);
  }

}
