package v1

import (
	"context"
	"encoding/json"
	"regexp"
	"strings"

	v1 "github.com/pingcap-inc/pingcat/model/v1"

	"github.com/pingcap-inc/pchub/pkg/log"
)

// PreValidateLarkMsg return false if the message doesn't need to be processed by ChatGPT.
func (s *ChatService) PreValidateLarkMsg(ctx context.Context, me *v1.LarkMsgEvent) bool {
	log.L(ctx).Info("ChatSrv.PreValidateLarkMsg called.")

	// validate message type
	if me.Message.MessageType != "text" {
		if me.Message.ChatType == v1.ChatTypeP2P {
			_, _ = s.SendTextLarkMsg(ctx, me, "Only plain text messages are supported now~")
		}

		return false
	}
	// validate message empty content
	var msgTextCont MsgTextCont
	if err := json.Unmarshal([]byte(me.Message.Content), &msgTextCont); err != nil {
		log.L(ctx).Error(err.Error())

		return false
	}
	if strings.TrimSpace(msgTextCont.Text) == "" {
		_, _ = s.SendTextLarkMsg(ctx, me, "Empty message is not supported~")

		return false
	}
	// omit @all
	atAllReg := regexp.MustCompile(`(^|\s+)@_all(\s+|$)`)
	if atAllReg.Match([]byte(msgTextCont.Text)) {
		return false
	}

	handled := s.handleIfCommand(ctx, me, msgTextCont.Text)
	if handled {
		return false
	}

	handled = s.handleRoute2APP(ctx, me, msgTextCont.Text)

	return !handled
}
