package wechat

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

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

type PhoneNumberResponse struct {
    ErrCode   int    `json:"errcode,omitempty"`
    ErrMsg    string `json:"errmsg,omitempty"`
    PhoneInfo struct {
        PhoneNumber     string `json:"phoneNumber"`
        PurePhoneNumber string `json:"purePhoneNumber"`
        CountryCode     string `json:"countryCode"`
    } `json:"phone_info"`
}

// GetPhoneNumber 使用微信开放接口换取用户手机号
// DOC: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-info/phone-number/getPhoneNumber.html
func GetPhoneNumber(ctx core.Context, accessToken, code string) (*PhoneNumberResponse, error) {
    if accessToken == "" || code == "" {
        return nil, fmt.Errorf("参数缺失")
    }
    client := httpclient.GetHttpClientWithContext(ctx.RequestContext())
    resp, err := client.R().
        SetQueryParam("access_token", accessToken).
        SetBody(map[string]string{"code": code}).
        Post("https://api.weixin.qq.com/wxa/business/getuserphonenumber")
    if err != nil {
        return nil, err
    }
    if resp.StatusCode() != http.StatusOK {
        return nil, fmt.Errorf("HTTP错误: %d", resp.StatusCode())
    }
    var r PhoneNumberResponse
    if err := json.Unmarshal(resp.Body(), &r); err != nil {
        return nil, err
    }
    if r.ErrCode != 0 {
        return nil, fmt.Errorf(r.ErrMsg)
    }
    if r.PhoneInfo.PurePhoneNumber == "" && r.PhoneInfo.PhoneNumber == "" {
        return nil, fmt.Errorf("未获取到手机号")
    }
    return &r, nil
}