package wechat

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"

	"bindbox-game/internal/pkg/httpclient"
)

type Code2SessionResponse struct {
	OpenID     string `json:"openid"`
	UnionID    string `json:"unionid,omitempty"`
	SessionKey string `json:"session_key"`
	ErrCode    int    `json:"errcode,omitempty"`
	ErrMsg     string `json:"errmsg,omitempty"`
}

func Code2Session(ctx context.Context, config *WechatConfig, code string) (*Code2SessionResponse, error) {
	if config == nil || config.AppID == "" || config.AppSecret == "" {
		fmt.Printf("DEBUG: Code2Session Config Missing: %+v\n", config)
		return nil, fmt.Errorf("微信配置缺失")
	}
	if code == "" {
		return nil, fmt.Errorf("code 不能为空")
	}
	client := httpclient.GetHttpClient()
	resp, err := client.R().
		SetContext(ctx).
		SetQueryParams(map[string]string{
			"appid":      config.AppID,
			"secret":     config.AppSecret,
			"js_code":    code,
			"grant_type": "authorization_code",
		}).
		Get("https://api.weixin.qq.com/sns/jscode2session")
	if err != nil {
		return nil, err
	}
	if resp.StatusCode() != http.StatusOK {
		return nil, fmt.Errorf("HTTP错误: %d", resp.StatusCode())
	}
	var r Code2SessionResponse
	if err := json.Unmarshal(resp.Body(), &r); err != nil {
		return nil, err
	}
	if r.ErrCode != 0 {
		return nil, fmt.Errorf(r.ErrMsg)
	}
	if r.OpenID == "" || r.SessionKey == "" {
		return nil, fmt.Errorf("响应缺少必要字段")
	}
	return &r, nil
}
