package apikey

import (
	"context"
	"encoding/base64"
	"strings"

	"github.com/tidbcloud/tiinf/errs"
)

const (
	akSkSeparator = ":"
)

func GenInnerApiKey(_ context.Context, ak, sk string) (string, error) {
	if ak == "" || sk == "" {
		return "", errs.NewBadRequest("ak/sk is blank", nil)
	}
	str := ak + akSkSeparator + sk
	enStr := base64.URLEncoding.EncodeToString([]byte(str))
	return enStr, nil
}

func ParseInnerApiKey(_ context.Context, apiKey string) (string, string, error) {
	if apiKey == "" {
		return "", "", errs.NewBadRequest("inner_api_key is blank", nil)
	}
	deBytes, err := base64.URLEncoding.DecodeString(apiKey)
	if err != nil {
		return "", "", errs.NewBadRequest("decode inner_api_key error", err)
	}
	str := string(deBytes)
	aksk := strings.Split(str, akSkSeparator)
	if len(aksk) != 2 {
		return "", "", errs.NewBadRequest("invalid inner_api_key", err)
	}
	ak := aksk[0]
	sk := aksk[1]
	return ak, sk, nil
}
