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

import com.paynicorn.sdk.model.InitPaymentRequest;
import com.paynicorn.sdk.model.InitPaymentResponse;
import com.red.circle.component.pay.paynicorn.service.PaynicornService;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.order.app.dto.clientobject.pay.PlaceAnOrderResponseCO;
import com.red.circle.tool.core.json.JacksonUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * Paynicorn 支付.
 *
 * @author pengliang on 2022/12/5
 */
@Slf4j
@Component("PAYNICORN_PLACE_AN_ORDER")
@RequiredArgsConstructor
public class PaynicornWebPayPlaceAnOrderStrategy implements
    PayWebPlaceAnOrderStrategyV2 {

  private final PaynicornService paynicornService;

  @Override
  public PlaceAnOrderResponseCO doOperation(PayPlaceAnOrderDetailsV2 details) {
    InitPaymentRequest request = new InitPaymentRequest();
    request.setAmount(details.getAmount().toString());
    request.setCountryCode(details.getCountryCode());
    request.setOrderId(details.getOrderId());
    request.setOrderDescription(details.getProductDescriptor());
    request.setCurrency(details.getCurrency());
    request.setPayMethod(details.getFactoryChannel());
    request.setCpFrontPage(details.getSuccessRedirectUrl());
    request.setMemo(JacksonUtils.toJson(details.createMetadata()));
    InitPaymentResponse response = paynicornService.createPayment(request);

    // 第三方api调用错误
    ResponseAssert.notNull(CommonErrorCode.THIRD_PARTY_SERVER_ERROR, response);

    return new PlaceAnOrderResponseCO()
        .setTradeNo(response.getTxnId())
        .setOrderId(request.getOrderId())
        .setCurrency(details.getCurrency())
        .setCountryCode(details.getCountryCode())
        .setFactoryCode(details.getFactoryCode())
        .setFactoryChannelCode(details.getFactoryChannel())
        .setRequestUrl(response.getWebUrl())
        .putRequestParam(request)
        .putResponseParam(response);
  }

}
