package dingtalk

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

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

type CardClient struct {
	cli          *card.Client
	oauth2Client *Oauth2Client
}

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

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

// 创建并投放卡片
func (c *CardClient) CreateAndDeliver(appKey AppKey, cardData *card.CreateAndDeliverRequest) (bool, error) {
	// 获取token
	accessToken, err := c.oauth2Client.GetAccessToken(appKey)
	if err != nil {
		return false, err
	}

	// 调用API
	resp, err := c.cli.CreateAndDeliverWithOptions(
		cardData,
		&card.CreateAndDeliverHeaders{XAcsDingtalkAccessToken: tea.String(accessToken)},
		&util.RuntimeOptions{},
	)
	if err != nil {
		return false, err
	}

	if resp.Body == nil {
		return false, errorcode.ParamErrf("empty response body")
	}
	if !*resp.Body.Success {
		return false, errorcode.ParamErrf("create and deliver failed")
	}

	return true, nil
}

// 更新卡片
func (c *CardClient) UpdateCard(appKey AppKey, cardData *card.UpdateCardRequest) (bool, error) {
	// 获取token
	accessToken, err := c.oauth2Client.GetAccessToken(appKey)
	if err != nil {
		return false, err
	}

	// 调用API
	resp, err := c.cli.UpdateCardWithOptions(
		cardData,
		&card.UpdateCardHeaders{XAcsDingtalkAccessToken: tea.String(accessToken)},
		&util.RuntimeOptions{},
	)
	if err != nil {
		return false, err
	}

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

	return *resp.Body.Success, nil
}
