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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.pengrad.telegrambot.TelegramBot;
import com.pengrad.telegrambot.model.PreCheckoutQuery;
import com.pengrad.telegrambot.model.SuccessfulPayment;
import com.pengrad.telegrambot.model.request.LabeledPrice;
import com.pengrad.telegrambot.request.CreateInvoiceLink;
import com.pengrad.telegrambot.response.StringResponse;
import com.pengrad.telegrambot.utility.BotUtils;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.dto.ReqAppIntel;
import com.red.circle.framework.core.dto.ReqSysOrigin;
import com.red.circle.order.app.dto.clientobject.pay.TelegramRechargeCO;
import com.red.circle.order.app.dto.cmd.TelegramPurchaseCmd;
import com.red.circle.order.app.dto.cmd.TelegramRechargeCmd;
import com.red.circle.order.app.service.InAppPurchaseProductService;
import com.red.circle.order.infra.database.rds.entity.order.OrderTelegramPurchase;
import com.red.circle.order.infra.database.rds.entity.product.ProductConfigV2;
import com.red.circle.order.infra.database.rds.service.order.OrderTelegramPurchaseService;
import com.red.circle.order.infra.database.rds.service.product.ProductConfigV2Service;
import com.red.circle.order.inner.asserts.OrderErrorCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Description:
 *
 * @date 2024/12/10 18:17
 */
@Slf4j
//@Service
@RequiredArgsConstructor
public class TelegramPurchaseService {

    private final InAppPurchaseProductService inAppPurchaseProductService;
    private final OrderTelegramPurchaseService orderTelegramPurchaseService;
    private final ProductConfigV2Service productConfigV2Service;
    private final TelegramBot telegramBot;
    private final Gson gson = BotUtils.GSON;

    public TelegramRechargeCO recharge(TelegramRechargeCmd cmd){

        ProductConfigV2 productConfig = productConfigV2Service.getById(cmd.getProductId());

        OrderTelegramPurchase orderTelegramPurchase = new OrderTelegramPurchase();
        orderTelegramPurchase.setSysOrigin(cmd.getReqSysOrigin().getOrigin());
        orderTelegramPurchase.setUserId(cmd.getReqUserId());
        orderTelegramPurchase.setProductId(cmd.getProductId());
        orderTelegramPurchase.setTitle(cmd.getTitle());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sysOrigin", productConfig.getSysOrigin());
        jsonObject.put("description", productConfig.getDescription());
        jsonObject.put("unitPrice", productConfig.getUnitPrice());
        jsonObject.put("obtainCandy", productConfig.getObtainCandy());
        jsonObject.put("rewardCandy", productConfig.getRewardCandy());
        jsonObject.put("platform", productConfig.getPlatform());
        orderTelegramPurchase.setProductDesc(jsonObject.toJSONString());

        orderTelegramPurchase.setPurchaseState(0);
        orderTelegramPurchase.setCurrency("XTR");
        orderTelegramPurchaseService.save(orderTelegramPurchase);

        CreateInvoiceLink request = new CreateInvoiceLink(cmd.getTitle(), cmd.getDescription(), orderTelegramPurchase.getId().toString(), "XTR", new LabeledPrice("XTR", productConfig.getUnitPrice().intValue()));
        log.info("telegram 下单请求{}", JSON.toJSONString(request));
        StringResponse response = telegramBot.execute(request);
        log.info("telegram 下单返回{}", response);
        ResponseAssert.isTrue(OrderErrorCode.VALIDATION_ORDER_FAILED, response.isOk());

        TelegramRechargeCO rechargeCO = new TelegramRechargeCO();
        rechargeCO.setUrl(response.result());
        return rechargeCO;
    }

    public void pay(PreCheckoutQuery preCheckoutQuery) {
        String invoicePayload = preCheckoutQuery.invoicePayload();
        OrderTelegramPurchase orderTelegramPurchase = orderTelegramPurchaseService.getById(invoicePayload);
        orderTelegramPurchase.setPreCheckId(preCheckoutQuery.id());
        orderTelegramPurchase.setFrom(gson.toJson(preCheckoutQuery.from()));
        orderTelegramPurchase.setPurchaseState(1);
        orderTelegramPurchaseService.updateSelectiveById(orderTelegramPurchase);
    }

    public void paySuccess(SuccessfulPayment successfulPayment) {
        String invoicePayload = successfulPayment.invoicePayload();
        OrderTelegramPurchase orderTelegramPurchase = orderTelegramPurchaseService.getById(invoicePayload);
        orderTelegramPurchase.setTelegramPaymentChargeId(successfulPayment.telegramPaymentChargeId());
        orderTelegramPurchase.setProviderPaymentChargeId(successfulPayment.providerPaymentChargeId());
        orderTelegramPurchaseService.updateSelectiveById(orderTelegramPurchase);

        TelegramPurchaseCmd cmd = new TelegramPurchaseCmd();
        cmd.setReqSysOrigin(ReqSysOrigin.of(orderTelegramPurchase.getSysOrigin()));
        cmd.setProduct(String.valueOf(orderTelegramPurchase.getProductId()));
        cmd.setReqUserId(orderTelegramPurchase.getUserId());
        cmd.setInvoicePayload(invoicePayload);
        cmd.setReqAppIntel(ReqAppIntel.parse("version=default1.0;build=1000;channel=Telegram;"));
        cmd.setReqTime(new Date());
        inAppPurchaseProductService.purchase(cmd);
    }

}
