package fuiou

import (
	"fmt"
	"time"

	"go.uber.org/zap"
)

// WxPreCreate 微信预下单（公众号JSAPI + 小程序）
// tradeType: "JSAPI"（公众号）或 "LETPAY"（小程序）
// subAppid: 公众号或小程序 AppID
// subOpenid: 用户在对应应用下的 OpenID
func (c *Client) WxPreCreate(orderNo, amount, goodsDesc, termIP, tradeType, subAppid, subOpenid string) (*WxPreCreateResponse, error) {
	req := &WxPreCreateRequest{
		Version:      "1.0",
		InsCd:        c.InsCd,
		MchntCd:      c.MchntCd,
		TermId:       c.TermId,
		RandomStr:    generateRandomStr(),
		MchntOrderNo: orderNo,
		TradeType:    tradeType,
		OrderAmt:     amount,
		GoodsDesc:    goodsDesc,
		TermIp:       termIP,
		TxnBeginTs:   time.Now().Format("20060102150405"),
		NotifyUrl:    c.NotifyURL,
		SubAppid:     subAppid,
		SubOpenid:    subOpenid,
	}

	sign, err := c.Sign(req)
	if err != nil {
		return nil, fmt.Errorf("签名失败: %w", err)
	}
	req.Sign = sign

	var resp WxPreCreateResponse
	if err := c.DoRequest("/wxPreCreate", req, &resp); err != nil {
		return nil, fmt.Errorf("请求富友失败: %w", err)
	}

	if resp.ResultCode != "000000" {
		c.logger.Error("富友预下单失败",
			zap.String("order_no", orderNo),
			zap.String("result_code", resp.ResultCode),
			zap.String("result_msg", resp.ResultMsg),
		)
		return nil, fmt.Errorf("富友预下单失败: %s", resp.ResultMsg)
	}

	c.logger.Info("富友预下单成功",
		zap.String("order_no", orderNo),
		zap.String("trade_type", tradeType),
	)

	return &resp, nil
}
