package feishu

import (
	"context"
	"errors"
	"fmt"
	"strings"

	larkcontact "github.com/larksuite/oapi-sdk-go/v3/service/contact/v3"
)

func GetUserPhoneNumber(ctx context.Context, cliParam FeishuCliParam, userId string) (string, error) {
	var receiveIdType string

	if strings.Contains(userId, "ou_") {
		receiveIdType = "open_id"
	} else if strings.Contains(userId, "oc_") {
		receiveIdType = "chat_id"
		return "", fmt.Errorf("cannot pass a chat_id: %s", userId)
	} else if strings.Contains(userId, "on_") {
		receiveIdType = "union_id"
		return "", fmt.Errorf("cannot pass a union_id: %s", userId)
	} else if strings.Contains(userId, "@") {
		receiveIdType = "email"
		return "", fmt.Errorf("cannot pass an email: %s", userId)
	} else {
		receiveIdType = "user_id"
	}

	req := larkcontact.NewGetUserReqBuilder().UserId(userId).UserIdType(receiveIdType).Build()
	larkClient := getClient(BotSetting{appId: cliParam.AppId, appSecret: cliParam.AppSecret})
	resp, err := larkClient.Contact.User.Get(ctx, req)
	if err != nil {
		return "", fmt.Errorf("get user error: %w", err)
	}
	if !resp.Success() {
		return "", errors.New(fmt.Sprint(resp.Code) + ": " + resp.Msg)
	}
	if resp.Data.User.Mobile == nil {
		return "", errors.New("mobile field for user is empty, may cause by privelege issues.")
	}

	phoneNum := *resp.Data.User.Mobile
	return phoneNum, nil
}
