package com.jeesharp.business.modules.pay.paywechatbill.application;

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.pay.api.PayBillChannelApi;
import com.jeesharp.business.modules.pay.bill.dto.PayBillApplyResultDTO;
import com.jeesharp.business.modules.pay.bill.dto.PayBillFundFlowApplyRequestDTO;
import com.jeesharp.business.modules.pay.bill.dto.PayBillTradeApplyRequestDTO;
import com.jeesharp.business.modules.pay.paywechatbill.vo.PayWechatBillFundFlowQueryVO;
import com.jeesharp.business.modules.pay.paywechatbill.vo.PayWechatBillTradeQueryVO;
import com.jeesharp.framework.exception.BizErrorException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 微信账单管理端应用服务：代理申请交易/资金账单下载地址。
 *
 * @author jeesharp
 * @since 2026-06-12
 */
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class PayWechatBillApplicationService {

    private final PayBillChannelApi payBillChannelApi;

    public PayBillApplyResultDTO applyTradeBill(PayWechatBillTradeQueryVO query) {
        PayBillTradeApplyRequestDTO request = new PayBillTradeApplyRequestDTO();
        request.setBillDate(query.getBillDate().trim());
        request.setBillType(StrUtil.blankToDefault(query.getBillType(), "ALL"));
        PayBillApplyResultDTO result = payBillChannelApi.applyTradeBill(request);
        assertSuccess(result);
        return result;
    }

    public PayBillApplyResultDTO applyFundFlowBill(PayWechatBillFundFlowQueryVO query) {
        PayBillFundFlowApplyRequestDTO request = new PayBillFundFlowApplyRequestDTO();
        request.setBillDate(query.getBillDate().trim());
        request.setAccountType(StrUtil.blankToDefault(query.getAccountType(), "BASIC"));
        PayBillApplyResultDTO result = payBillChannelApi.applyFundFlowBill(request);
        assertSuccess(result);
        return result;
    }

    private static void assertSuccess(PayBillApplyResultDTO result) {
        if (result == null || !Boolean.TRUE.equals(result.getSuccess())) {
            throw new BizErrorException(result != null && StrUtil.isNotBlank(result.getErrorMsg())
                    ? result.getErrorMsg() : "申请账单失败");
        }
    }
}
