package services

import (
	"errors"
	"strings"
	"testing"

	waProto "go.mau.fi/whatsmeow/proto/waE2E"
	"go.mau.fi/whatsmeow/types/events"
	"google.golang.org/protobuf/proto"
)

func TestNativeMenuRemainsVisibleAndDoesNotActAsCustomerClick(t *testing.T) {
	msg, err := replyButtonsMessage("Pilih layanan", "Pilih salah satu", []ReplyButton{{ID: "flow:one", Text: "Katalog"}, {ID: "flow:two", Text: "Jam layanan"}})
	if err != nil {
		t.Fatal(err)
	}
	wrapped := &waProto.Message{ViewOnceMessage: &waProto.FutureProofMessage{Message: msg}}
	w := &waInstance{}
	in, ok := w.extractIncoming(&events.Message{Message: wrapped})
	if !ok || in.ActionID != "" || !strings.Contains(in.Text, "• Katalog") || !strings.Contains(in.Text, "• Jam layanan") {
		t.Fatalf("menu lost or treated as a click: %+v", in)
	}
	text, _, _, _, _, _ := historicalMessageContent(wrapped)
	if text != in.Text {
		t.Fatalf("history differs: %q vs %q", text, in.Text)
	}
	for _, buttons := range [][]ReplyButton{nil, {{ID: "1", Text: ""}}, {{ID: "1", Text: "A"}, {ID: "1", Text: "B"}}, {{ID: "1", Text: "A"}, {ID: "2", Text: "B"}, {ID: "3", Text: "C"}, {ID: "4", Text: "D"}}} {
		if _, err := replyButtonsMessage("Menu", "", buttons); err == nil {
			t.Fatal("invalid buttons accepted", buttons)
		}
	}
}

func TestAutomaticButtonsStopBeforeSendingOnOperatorTakeover(t *testing.T) {
	stop := errors.New("taken over")
	id, err := (&waInstance{}).SendButtonsWithDelayAndGetID("628111111111", "Menu", "", []ReplyButton{{ID: "1", Text: "Katalog"}}, 2, 4, func() error { return stop })
	if id != "" || !errors.Is(err, stop) {
		t.Fatal("operator guard bypassed", id, err)
	}
}

func TestInteractiveReplyTextNativeFlowDisplayText(t *testing.T) {
	msg := &waProto.Message{
		InteractiveResponseMessage: &waProto.InteractiveResponseMessage{
			InteractiveResponseMessage: &waProto.InteractiveResponseMessage_NativeFlowResponseMessage_{
				NativeFlowResponseMessage: &waProto.InteractiveResponseMessage_NativeFlowResponseMessage{
					ParamsJSON: proto.String(`{"id":"product_order","display_text":"Pesan Sekarang"}`),
				},
			},
		},
	}

	text, actionID, _, ok := interactiveReplyText(msg)
	if !ok || text != "Pesan Sekarang" {
		t.Fatalf("respons tombol tidak terbaca: ok=%v text=%q", ok, text)
	}
	if actionID != "product_order" {
		t.Fatalf("action ID tombol tidak terbaca: %q", actionID)
	}
}

func TestInteractiveReplyTextNativeFlowIDFallback(t *testing.T) {
	msg := &waProto.Message{
		InteractiveResponseMessage: &waProto.InteractiveResponseMessage{
			InteractiveResponseMessage: &waProto.InteractiveResponseMessage_NativeFlowResponseMessage_{
				NativeFlowResponseMessage: &waProto.InteractiveResponseMessage_NativeFlowResponseMessage{
					ParamsJSON: proto.String(`{"id":"product_question"}`),
				},
			},
		},
	}

	text, actionID, _, ok := interactiveReplyText(msg)
	if !ok || text != "Tanya Detail" {
		t.Fatalf("ID tombol tidak dipetakan: ok=%v text=%q", ok, text)
	}
	if actionID != "product_question" {
		t.Fatalf("action ID tombol tidak terbaca: %q", actionID)
	}
}

func TestInteractiveReplyTextLegacyButton(t *testing.T) {
	msg := &waProto.Message{
		ButtonsResponseMessage: &waProto.ButtonsResponseMessage{
			Response: &waProto.ButtonsResponseMessage_SelectedDisplayText{SelectedDisplayText: "Pesan Sekarang"},
		},
	}

	text, _, _, ok := interactiveReplyText(msg)
	if !ok || text != "Pesan Sekarang" {
		t.Fatalf("respons tombol lama tidak terbaca: ok=%v text=%q", ok, text)
	}
}

func TestNativeFlowBizNodes(t *testing.T) {
	nodes := nativeFlowBizNodes()
	if len(nodes) != 1 || nodes[0].Tag != "biz" {
		t.Fatalf("node bisnis native flow tidak valid: %+v", nodes)
	}
	interactive := nodes[0].GetChildrenByTag("interactive")
	if len(interactive) != 1 || interactive[0].Attrs["type"] != "native_flow" || interactive[0].Attrs["v"] != "1" {
		t.Fatalf("metadata interactive tidak valid: %+v", interactive)
	}
	nativeFlow := interactive[0].GetChildrenByTag("native_flow")
	if len(nativeFlow) != 1 || nativeFlow[0].Attrs["name"] != "mixed" || nativeFlow[0].Attrs["v"] != "9" {
		t.Fatalf("metadata native flow tidak valid: %+v", nativeFlow)
	}
}
