const { request } = require('./request');

const createVipOrder = async ({ planId, duration }) => {
  const res = await request({
    url: '/api/payment/vip',
    method: 'POST',
    data: { planId, duration, paymentMethod: 'wechat' }
  });
  const body = res.data || {};
  if (!body.success) throw new Error(body.error || '创建VIP订单失败');
  return body.data;
};

const createProductOrder = async ({ productId, referralCode }) => {
  const res = await request({
    url: `/api/products/${productId}/purchase`,
    method: 'POST',
    data: { payment_method: 'wechat', ...(referralCode ? { referral_code: referralCode } : {}) }
  });
  const body = res.data || {};
  if (!body.success) throw new Error(body.error || '创建订单失败');
  const data = body.data || {};
  return {
    orderId: data.order_id,
    orderNo: data.order_no,
    amount: data.amount,
    productName: data.product_name,
    expireAt: data.expire_at
  };
};

const getPrepayParams = async ({ orderId, orderType }) => {
  const res = await request({
    url: '/api/payment/prepay',
    method: 'POST',
    data: { orderId, orderType }
  });
  const body = res.data || {};
  if (!body.success) throw new Error(body.error || '获取支付参数失败');
  return body.data;
};

const requestPayment = async (params) => {
  return new Promise((resolve, reject) => {
    const paymentArgs = {
      timeStamp: String(params.timeStamp),
      nonceStr: params.nonceStr,
      package: params.package,
      signType: params.signType,
      paySign: params.paySign,
      // 部分老旧兼容可能需要 total_fee，尝试带上
      ...(params.total_fee ? { total_fee: params.total_fee } : {})
    };

    console.log('[Payment] Requesting wx.requestPayment with:', JSON.stringify(paymentArgs));

    wx.requestPayment({
      ...paymentArgs,
      success: (res) => {
        console.log('[Payment] Success:', res);
        resolve(res);
      },
      fail: (err) => {
        console.error('[Payment] Fail:', err);
        // 转换错误信息
        const msg = err.errMsg || '';
        if (msg.includes('parameter error') || msg.includes('missing parameter')) {
          console.error('[Payment] Parameter Error Details:', paymentArgs);
        }
        reject(err);
      }
    });
  });
};

const payVip = async ({ planId, duration }) => {
  const order = await createVipOrder({ planId, duration });
  const prepay = await getPrepayParams({ orderId: order.orderId, orderType: 'vip' });
  await requestPayment(prepay);
  return order;
};

const payProduct = async ({ productId, orderType, referralCode }) => {
  const order = await createProductOrder({ productId, referralCode });
  const prepay = await getPrepayParams({ orderId: order.orderId, orderType });
  await requestPayment(prepay);
  return order;
};

module.exports = {
  payVip,
  payProduct
};
