package http

import (
	"time"

	"quyun/app/models"
	"quyun/database/schemas/public/model"
	"quyun/providers/wechat"

	"github.com/gofiber/fiber/v3"
	"github.com/gofiber/fiber/v3/log"
)

// @provider
type wechats struct {
	wechat *wechat.Client
}

// GetJsSDK
// @Router /wechats/js-sdk [get]
// @Bind url query
// @Bind user local
func (ctl *wechats) GetJsSDK(ctx fiber.Ctx, url string, user *model.Users) (*wechat.JsSDK, error) {
	if user.AuthToken.Data.StableExpiresAt.Before(time.Now()) {
		token, err := ctl.wechat.RefreshAccessToken(user.AuthToken.Data.RefreshToken)
		if err != nil {
			return nil, err
		}
		log.Infof("refresh token: %+v", token)

		stableToken, err := ctl.wechat.GetStableAccessToken()
		if err != nil {
			return nil, err
		}
		user.AuthToken.Data.StableAccessToken = stableToken.AccessToken

		oldToken := user.AuthToken.Data
		oldToken.AccessToken = token.AccessToken
		oldToken.ExpiresAt = time.Now().Add(time.Second * time.Duration(token.ExpiresIn))

		oldToken.StableAccessToken = stableToken.AccessToken
		oldToken.StableExpiresAt = time.Now().Add(time.Second * time.Duration(stableToken.ExpiresIn))

		if err := models.Users.UpdateUserToken(ctx.Context(), user.ID, oldToken); err != nil {
			return nil, err
		}
		user.AuthToken.Data = oldToken
	}

	return ctl.wechat.GetJsSDK(user.AuthToken.Data.StableAccessToken, url)
}
