package dingtalk

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

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

type ImClient struct {
	cli          *im.Client
	oauth2Client *Oauth2Client
}

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

	return &ImClient{cli: c, oauth2Client: oauth2Client}, nil
}

// 创建并投放卡片
func (c *ImClient) AddRobotToConversation(appKey AppKey, imData *im.AddRobotToConversationRequest) (string, error) {
	// 获取token
	accessToken, err := c.oauth2Client.GetAccessToken(appKey)
	if err != nil {
		return "", err
	}

	// 调用API
	resp, err := c.cli.AddRobotToConversationWithOptions(
		imData,
		&im.AddRobotToConversationHeaders{XAcsDingtalkAccessToken: tea.String(accessToken)},
		&util.RuntimeOptions{},
	)
	if err != nil {
		return "", err
	}

	if resp.Body == nil {
		return "", errorcode.ParamErrf("empty response body")
	}

	return *resp.Body.ChatBotUserId, nil
}

// 创建场景群 不返回chatid，如果没有获取群聊分享链接的诉求，可以使用该接口
func (c *ImClient) CreateSceneGroup(appKey AppKey, req *im.CreateSceneGroupConversationRequest) (openConversationId string, err error) {
	// 获取token
	accessToken, err := c.oauth2Client.GetAccessToken(appKey)
	if err != nil {
		return "", err
	}

	// 调用API
	resp, err := c.cli.CreateSceneGroupConversationWithOptions(
		req,
		&im.CreateSceneGroupConversationHeaders{XAcsDingtalkAccessToken: tea.String(accessToken)},
		&util.RuntimeOptions{},
	)
	if err != nil {
		return "", err
	}

	if resp.Body == nil {
		return "", errorcode.ParamErrf("empty response body")
	}

	return *resp.Body.OpenConversationId, nil
}
