package dingtalk

import (
	errorcode "ai_scheduler/internal/data/error"

	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	contact "github.com/alibabacloud-go/dingtalk/contact_1_0"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
)

type ContactClient struct {
	cli          *contact.Client
	oauth2Client *Oauth2Client
}

func NewContactClient(oauth2Client *Oauth2Client) (*ContactClient, error) {
	cfg := &openapi.Config{
		Protocol: tea.String("https"),
		RegionId: tea.String("central"),
	}
	c, err := contact.NewClient(cfg)
	if err != nil {
		return nil, err
	}
	return &ContactClient{cli: c, oauth2Client: oauth2Client}, nil
}

type SearchUserReq struct {
	FullMatchField int32
	QueryWord      string
	Offset         int32
	Size           int32
}

type SearchUserResp struct {
	Body interface{}
}

func (c *ContactClient) SearchUserOne(appKey AppKey, name string) (string, error) {
	// 获取token
	accessToken, err := c.oauth2Client.GetAccessToken(appKey)
	if err != nil {
		return "", err
	}

	resp, err := c.cli.SearchUserWithOptions(
		&contact.SearchUserRequest{
			FullMatchField: tea.Int32(1),
			QueryWord:      tea.String(name),
			Offset:         tea.Int32(0),
			Size:           tea.Int32(1),
		},
		&contact.SearchUserHeaders{XAcsDingtalkAccessToken: tea.String(accessToken)},
		&util.RuntimeOptions{},
	)
	if err != nil {
		return "", err
	}

	if resp.Body == nil {
		return "", errorcode.ParamErrf("empty response body")
	}
	if len(resp.Body.List) == 0 {
		return "", errorcode.ParamErrf("empty user list")
	}
	userId := resp.Body.List[0]

	return *userId, nil
}
