package marketing

import (
	"context"
	"encoding/json"
	"net/http"
	"net/url"
	"strings"
	"voucher/internal/pkg/wechat/srv"
	"voucher/internal/pkg/wechat/utils"
)

const (
	sendPath  = "/v3/marketing/bank-favor/users/{openid}/bank-multi-activity"
	queryPath = "/v3/marketing/bank-favor/users/{openid}/coupons/{coupon_id}"
)

// Marketing 产品介绍 https://docs.qq.com/doc/DSUJPTEhrc0Npb2Zj?_t=1743576271598&nlc=1
type Marketing srv.Srv

// Send @link https://pay.weixin.qq.com/doc/v3/merchant/4014569793
func (srv *Marketing) Send(openId string, req *SendReq) (response *SendResp, err error) {

	reqBody, err := json.Marshal(&req)
	if err != nil {
		return nil, err
	}

	path := strings.Replace(sendPath, "{openid}", url.PathEscape(openId), -1)

	respBody, err := srv.Request2(utils.Host, utils.MethodPOST, path, reqBody)
	if err != nil {
		return nil, err
	}

	if err = json.Unmarshal(respBody, &response); err != nil {
		return nil, err
	}

	return response, nil
}

// Query @link https://pay.weixin.qq.com/doc/v3/merchant/4014569864
func (srv *Marketing) Query(appId, openId, couponId string) (response *SendResp, err error) {

	path := strings.Replace(queryPath, "{openid}", url.PathEscape(openId), -1)
	path = strings.Replace(path, "{coupon_id}", url.PathEscape(couponId), -1)

	var uv = url.Values{}
	uv.Set("appid", appId)
	path += "?" + uv.Encode()

	respBody, err := srv.Request2(utils.Host, utils.MethodGET, path, nil)
	if err != nil {
		return nil, err
	}

	if err = json.Unmarshal(respBody, &response); err != nil {
		return nil, err
	}

	return response, nil
}

func (srv *Marketing) Notify(_ context.Context, headers *http.Header, respBody []byte) (body *utils.WxNotifyBody, response string, err error) {

	wxNotifyBody, err := srv.GetNotifyBody(headers, respBody)
	if err != nil {
		return nil, "", err
	}

	bizStr, err := srv.DecodeBody(wxNotifyBody)
	if err != nil {
		return nil, "", err
	}

	return wxNotifyBody, bizStr, nil
}
