package thirdparty

import (
	"context"
	"encoding/json"
	"fmt"
	"os"

	"github.com/tidbcloud/auth-server/commons/utils"

	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"
	"net/http"
)

func GetTmsUsername(ctx context.Context, email string) (*TmsUser, error) {

	//url := "/api/v1/users/email:zhanghao@pingcap.com"
	host := "https://pingcapedu.talentlms.com"
	url := "/api/v1/users/email:" + email

	method := http.MethodGet

	tmsKey := os.Getenv("TMS_KEY")

	header := map[string]string{
		"Content-Type":  "application/json",
		"Authorization": fmt.Sprintf("Basic %s", tmsKey),
	}

	resp, err := utils.HttpRequest(ctx, *utils.NewHttpConfig(host, url, method, header))
	if err != nil {
		tilog.Error(ctx, "failed to call tms getTmsUsername", zap.Error(err))
		return nil, err
	}

	var tmsUser TmsUser

	err = json.Unmarshal([]byte(resp), &tmsUser)
	if err != nil {
		tilog.Error(ctx, "failed to json.Unmarshal", zap.Error(err))
		return nil, err
	}
	if tmsUser.Login == "" {
		tilog.Info(ctx, email+" not exist in talentlms ")
		return nil, nil
	}
	tilog.Info(ctx, "GetTmsUsername from talentlms ", zap.Any("tmsUser", tmsUser))
	return &tmsUser, err

}
