package wechat

import (
	"context"
	"encoding/json"
	"errors"
	"io"
	"log"
	"sundynix-go/global"
	"sundynix-go/pkg/httpclient"
	"time"

	"github.com/redis/go-redis/v9"
)

// GetMiniAccessToken 获取小程序的access_token
func GetMiniAccessToken() string {
	ak, err := global.Redis.Get(context.Background(), "zeeq_mini_access_token").Result()
	if errors.Is(err, redis.Nil) {
		// 从微信服务器获取
		//重新从微信服务器获取
		url := "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + global.Config.MiniProgram.AppId + "&secret=" + global.Config.MiniProgram.AppSecret
		myHttpClient := httpclient.GetClient()
		resp, err := myHttpClient.Get(url)
		if err != nil {
			log.Fatalf("Error making GET request: %s", err)
		}
		defer func(Body io.ReadCloser) {
			err := Body.Close()
			if err != nil {
				log.Fatalf("Error closing response body: %s", err)
			}
		}(resp.Body)
		body, err := io.ReadAll(resp.Body)
		if err != nil {
			log.Fatalf("Error reading response body: %s", err)
		}
		res := string(body)

		var data map[string]interface{}
		err = json.Unmarshal([]byte(res), &data)
		if err != nil {
			log.Fatalf("Error unmarshalling JSON: %s", err)
		}
		ak = data["access_token"].(string)
		ex := data["expires_in"].(float64)
		global.Redis.Set(context.Background(), "zeeq_mini_access_token", ak, time.Duration(ex)*time.Second) //秒
	} else if err != nil {
		log.Fatalf("Error getting access token from Redis: %s", err)
	}
	return ak

}
