package admin

import (
	"encoding/base64"
	"net/http"
	"net/url"

	"bindbox-game/internal/code"
	"bindbox-game/internal/pkg/core"
	"bindbox-game/internal/pkg/validation"
	"bindbox-game/internal/pkg/wechat"
	"bindbox-game/internal/service/sysconfig"
)

type miniappQRCodeRequest struct {
	InviteCode  string `json:"invite_code"`
	DouyinID    string `json:"douyin_id"`
	ChannelCode string `json:"channel_code"`
	Width       *int   `json:"width"`
}

type miniappQRCodeResponse struct {
	ImageBase64 string `json:"image_base64"`
}

func (h *handler) GenerateMiniAppQRCode() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(miniappQRCodeRequest)
		if err := ctx.ShouldBindJSON(req); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, validation.Error(err)))
			return
		}

		q := url.Values{}
		if req.InviteCode != "" {
			q.Set("invite_code", req.InviteCode)
		}
		if req.DouyinID != "" {
			q.Set("douyin_id", req.DouyinID)
		}
		if req.ChannelCode != "" {
			q.Set("channel_code", req.ChannelCode)
		}

		if len(q) == 0 {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, "参数不能为空"))
			return
		}

		path := "/pages/login/index?" + q.Encode()

		// 使用动态配置
		dc := sysconfig.GetDynamicConfig()
		wxConfig := dc.GetWechat(ctx.RequestContext())

		wxcfg := &wechat.WechatConfig{AppID: wxConfig.AppID, AppSecret: wxConfig.AppSecret}
		qReq := &wechat.QRCodeRequest{Path: path}
		if req.Width != nil {
			qReq.Width = *req.Width
		}
		rsp, err := wechat.GetQRCodeWithConfig(ctx, wxcfg, qReq)
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 12001, err.Error()))
			return
		}
		out := &miniappQRCodeResponse{ImageBase64: base64.StdEncoding.EncodeToString(rsp.Buffer)}
		ctx.Payload(out)
	}
}
