package qq_message

import (
	"encoding/json"
	"fmt"
	"regexp"
)

// ForwardMessage 转发消息
type ForwardMessage struct {
	Type string             `json:"type"`
	Data ForwardMessageData `json:"data"`
}

type ForwardMessageData struct {
	ID      string `json:"id"`                // 转发消息ID
	Content []any  `json:"content,omitempty"` // 转发消息内容
}

// NodeMessage 转发消息节点
type NodeMessage struct {
	Type string          `json:"type"`
	Data NodeMessageData `json:"data"`
}

type NodeMessageData struct {
	ID       string `json:"id,omitempty"`       // 转发消息ID
	UserID   string `json:"user_id,omitempty"`  // 发送者QQ号
	Nickname string `json:"nickname,omitempty"` // 发送者昵称
	Content  []any  `json:"content,omitempty"`  // 消息内容
}

func init() {
	RegisterMessageType(TypeForward, func() QQMessage {
		return NewForwardMessage()
	})
	RegisterMessageType(TypeNode, func() QQMessage {
		return NewNodeMessage()
	})
}

func NewForwardMessage() *ForwardMessage {
	return &ForwardMessage{Type: TypeForward}
}

func (msg *ForwardMessage) GetMessageType() string {
	return TypeForward
}

// ForwardMessage methods
func (msg *ForwardMessage) SetData(data json.RawMessage) error {
	return json.Unmarshal(data, &msg.Data)
}

func NewNodeMessage() *NodeMessage {
	return &NodeMessage{Type: TypeNode}
}

func (msg *NodeMessage) GetMessageType() string {
	return TypeNode
}

func (msg *ForwardMessage) ToCQString() string {
	return fmt.Sprintf("[CQ:forward,id=%s]", msg.Data.ID)
}

func (msg *ForwardMessage) ParseMessage(data string) error {
	re := regexp.MustCompile(`\[CQ:forward,id=(.*?)\]`)
	matches := re.FindStringSubmatch(data)
	if len(matches) < 2 {
		return fmt.Errorf("转发消息格式不正确")
	}
	msg.Data.ID = matches[1]
	return nil
}

// NodeMessage methods
func (msg *NodeMessage) SetData(data json.RawMessage) error {
	return json.Unmarshal(data, &msg.Data)
}

func (msg *NodeMessage) ToCQString() string {
	if msg.Data.ID != "" {
		return fmt.Sprintf("[CQ:node,id=%s]", msg.Data.ID)
	}
	return fmt.Sprintf("[CQ:node,user_id=%s,nickname=%s]", msg.Data.UserID, msg.Data.Nickname)
}

func (msg *NodeMessage) ParseMessage(userId string, nickname string, content []any) *NodeMessage {
	msg.Data.UserID = userId
	msg.Data.Nickname = nickname
	msg.Data.Content = content
	return msg
}
