package service

import (
	"encoding/json"
	"errors"
	"sec-cycle-scan/common"
	"sec-cycle-scan/utils"
	"time"
)

type InteractiveMessage struct {
	MsgType string `json:"msg_type"`
	Card    struct {
		Config   Config    `json:"config"`
		Header   Header    `json:"header"`
		Elements []Element `json:"elements"`
	} `json:"card"`
}

type Config struct {
	WideScreenMode bool `json:"wide_screen_mode"`
}

type Header struct {
	Template string `json:"template"`
	Title    Title  `json:"title"`
}

type Title struct {
	Tag     string `json:"tag"`
	Content string `json:"content"`
}

type Element struct {
	Tag     string   `json:"tag"`
	Bold    bool     `json:"bold,omitempty"`
	Content string   `json:"content,omitempty"`
	Fields  []Field  `json:"fields,omitempty"`
	Actions []Action `json:"actions,omitempty"`
}

type Field struct {
	IsShort bool `json:"is_short"`
	Text    Text `json:"text"`
}

type Text struct {
	Tag     string `json:"tag"`
	Content string `json:"content"`
}

type Action struct {
	Tag  string `json:"tag"`
	Text Text   `json:"text"`
	Type string `json:"type"`
	URL  string `json:"url"`
}

type FeiShuResp struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

// SendFeiShuMessage sends a message to Feishu webhook
func SendFeiShuMessage(message InteractiveMessage) error {

	webhookURL := common.CONFIG.System.LarkUrl

	hc := &utils.HConfig{
		Timeout: 10 * time.Second,
	}
	httpClient := hc.NewHTTPClient()
	res, err := httpClient.Post(webhookURL, nil, message)
	if err != nil {
		return err
	}

	var resp FeiShuResp
	if err := json.Unmarshal(res, &resp); err != nil {
		return err
	}

	if resp.Code != 0 {
		return errors.New(resp.Msg)
	}

	return nil
}
