package core

import (
	"errors"
	"github.com/ArtisanCloud/MediaX/internal/kernel"
	"github.com/ArtisanCloud/MediaX/pkg/client/config"
	"github.com/ArtisanCloud/MediaXCore/pkg/cache"
	config2 "github.com/ArtisanCloud/MediaXCore/pkg/config"
	"github.com/ArtisanCloud/MediaXCore/pkg/logger"
	"github.com/ArtisanCloud/MediaXCore/utils/object"
)

type WeChatAccessTokenHandler struct {
	Config             *config.ClientConfig
	ClientTokenHandler *kernel.TokenHandler
}

func NewWeChatAccessTokenHandler(cfg *config.ClientConfig, logger *logger.Logger, cache cache.ICache) (*WeChatAccessTokenHandler, error) {
	if cfg == nil {
		return nil, errors.New("wechat cfg is nil")
	}
	if cfg.ApiUrl == "" {
		cfg.ApiUrl = config.WechatAppAPIUrl
	}
	handler, err := kernel.NewTokenHandler(cfg, logger, cache)
	if err != nil {
		return nil, err
	}
	wechatHandler := &WeChatAccessTokenHandler{
		Config:             cfg,
		ClientTokenHandler: handler,
	}

	if cfg.AccessTokenUrl != "" {
		wechatHandler.ClientTokenHandler.EndpointToGetToken = cfg.AccessTokenUrl
	} else {
		wechatHandler.ClientTokenHandler.EndpointToGetToken = config.WechatAuthTokenUrl
	}
	wechatHandler.OverrideGetCredentials()

	return wechatHandler, nil
}

func (acHandler *WeChatAccessTokenHandler) OverrideGetCredentials() {

	acHandler.ClientTokenHandler.GetCredentials = func() *object.StringMap {
		return &object.StringMap{
			"grant_type": string(config2.AuthFlowClientCred),
			"appid":      acHandler.Config.ClientID,
			"secret":     acHandler.Config.ClientSecret,
			"neededText": "",
		}
	}
}
