package http

import (
	"context"
	"strconv"
)

func GetJwtByApiKey(ctx context.Context, clusterId uint64, accessKey string) (resp *GetJwtByApiKeyResp, err error) {
	url := "/inner/account-central/api/v1/apikey-jwt"
	req := map[string]string{
		"cluster_id": strconv.FormatUint(clusterId, 10),
		"access_key": accessKey,
	}
	resp = &GetJwtByApiKeyResp{}
	err = getFromAccountCentral(ctx, url, req, resp)
	return
}

func GetJwtByToken(ctx context.Context, clusterId uint64, auth0Token string) (resp *GetJwtByTokenResp, err error) {
	url := "/inner/account-central/api/v1/user-jwt"
	req := map[string]string{
		"cluster_id":  strconv.FormatUint(clusterId, 10),
		"auth0_token": auth0Token,
	}
	resp = &GetJwtByTokenResp{}
	err = getFromAccountCentral(ctx, url, req, resp)
	return
}

func GetJwtByEmail(ctx context.Context, clusterId uint64, email string) (resp *GetJwtByTokenResp, err error) {
	url := "/inner/account-central/api/v1/user-jwt"
	req := map[string]string{
		"cluster_id": strconv.FormatUint(clusterId, 10),
		"email":      email,
	}
	resp = &GetJwtByTokenResp{}
	err = getFromAccountCentral(ctx, url, req, resp)
	return
}

func getFromAccountCentral(ctx context.Context, url string, req map[string]string, resp interface{}) (err error) {
	defer func() {
		recordHttpCounterMetric("account-central", err)
	}()
	return getRequestToGlobal(ctx, "account-central", url, req, resp)
}

type BaseResp struct {
	ErrCode string `json:"err_code"`
	ErrMsg  string `json:"err_msg"`
}

func (r *BaseResp) GetErrCode() int {
	code, _ := strconv.Atoi(r.ErrCode)
	return code
}
func (r *BaseResp) GetErrMsg() string {
	return r.ErrMsg
}

type GetJwtByApiKeyResp struct {
	Jwt    string   `json:"jwt"`
	DbUser string   `json:"db_user"`
	Base   BaseResp `json:"base_resp"`
}

func (r *GetJwtByApiKeyResp) GetErrCode() int {
	return r.Base.GetErrCode()
}
func (r *GetJwtByApiKeyResp) GetErrMsg() string {
	return r.Base.GetErrMsg()
}

type GetJwtByTokenResp struct {
	Jwt    string   `json:"jwt"`
	DbUser string   `json:"db_user"`
	Base   BaseResp `json:"base_resp"`
}

func (r *GetJwtByTokenResp) GetErrCode() int {
	return r.Base.GetErrCode()
}
func (r *GetJwtByTokenResp) GetErrMsg() string {
	return r.Base.GetErrMsg()
}
