package handlers

import (
	"net/http"

	"otaupdate/services"

	"github.com/fiskerinc/cloud-services/pkg/redis"
	"github.com/fiskerinc/cloud-services/pkg/superset"
	"github.com/fiskerinc/cloud-services/pkg/utils"
	"github.com/fiskerinc/cloud-services/pkg/loggerdataresp"
)

type GuestTokenResp struct {
	Token string `json:"token"`
}

var (
	getAccessTokenFunc = superset.GetAccessToken
	getGuestTokenFunc  = superset.GetGuestToken
)

// HandleDashboardToken godoc
// @Summary Get token for accessing dashboard
// @Description Returns token
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Success 200 {object} GuestTokenResp
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /dashboard/guest-token [get]
func HandleDashboardToken(w http.ResponseWriter, r *http.Request) {
	redisClient := services.RedisClientPool().GetFromPool()
	defer redisClient.Close()

	accToken, err := getAccessTokenFunc(redisClient)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
		return
	}

	guestToken, err := getGuestTokenFunc(redisClient, accToken)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
		return
	}

	utils.RespJSON(w, http.StatusOK, GuestTokenResp{Token: guestToken})
}

func SetGetAccessTokenFunc(f func(r redis.Client) (string, error)) {
	getAccessTokenFunc = f
}

func SetGetGuestTokenFunc(f func(r redis.Client, accToken string) (string, error)) {
	getGuestTokenFunc = f
}
