package impl

import (
	"ai_scheduler/internal/data/model"
	"ai_scheduler/internal/entitys"
	"ai_scheduler/internal/pkg/dingtalk"
	"ai_scheduler/tmpl/dataTemp"
	"ai_scheduler/utils"
	"encoding/json"

	"xorm.io/builder"
)

type BotConfigImpl struct {
	dataTemp.DataTemp
}

func NewBotConfigImpl(db *utils.Db) *BotConfigImpl {
	return &BotConfigImpl{
		DataTemp: *dataTemp.NewDataTemp(db, new(model.AiBotConfig)),
	}
}

// GetRobotConfig 获取机器人配置
func (b *BotConfigImpl) GetRobotConfig(robotCode string) (*entitys.DingTalkBot, error) {
	// 获取机器人配置
	var botConfig model.AiBotConfig
	cond := builder.NewCond().And(builder.Eq{"robot_code": robotCode}).And(builder.Eq{"status": 1})
	err := b.GetOneBySearchToStrut(&cond, &botConfig)
	if err != nil {
		return nil, err
	}
	// 解出 config
	var config entitys.DingTalkBot
	err = json.Unmarshal([]byte(botConfig.BotConfig), &config)
	if err != nil {
		return nil, err
	}

	return &config, nil
}

// GetRobotAppKey 获取机器人应用ID
func (b *BotConfigImpl) GetRobotAppKey(robotCode string) (dingtalk.AppKey, error) {
	// 获取机器人配置
	dingTalkBotConfig, err := b.GetRobotConfig(robotCode)
	if err != nil {
		return dingtalk.AppKey{}, err
	}

	return dingTalkBotConfig.GetAppKey(), nil
}
