package services

import (
	"go.mau.fi/whatsmeow"
	"go.mau.fi/whatsmeow/proto/waCommon"
	"go.mau.fi/whatsmeow/proto/waE2E"
	waHistorySync "go.mau.fi/whatsmeow/proto/waHistorySync"
	"go.mau.fi/whatsmeow/proto/waWeb"
	"go.mau.fi/whatsmeow/store"
	"go.mau.fi/whatsmeow/types"
	"go.mau.fi/whatsmeow/types/events"
	"google.golang.org/protobuf/proto"
	"testing"
	"time"
)

func TestInboxHistoryKeepsServiceChatsAndSystemOnlyGroups(t *testing.T) {
	oldSync, oldState := onHistorySync, onHistoryChatState
	t.Cleanup(func() { onHistorySync, onHistoryChatState = oldSync, oldState })
	var messages []HistoricalMessage
	var states []HistoryChatState
	onHistorySync = func(_ uint, rows []HistoricalMessage) (int, int, error) {
		messages = append(messages, rows...)
		return len(rows), 0, nil
	}
	onHistoryChatState = func(_ uint, rows []HistoryChatState) { states = append(states, rows...) }
	at := time.Date(2026, 9, 26, 9, 0, 0, 0, time.UTC)
	group := "120363000000001@g.us"
	self := types.NewJID("628111111111", types.DefaultUserServer)
	w := &waInstance{client: &whatsmeow.Client{Store: &store.Device{ID: &self}}}
	w.processHistorySync(&events.HistorySync{Data: &waHistorySync.HistorySync{Progress: proto.Uint32(100), Conversations: []*waHistorySync.Conversation{
		{ID: proto.String(group), Name: proto.String("Grup Member"), ConversationTimestamp: proto.Uint64(uint64(at.Unix())), Messages: []*waHistorySync.HistorySyncMsg{{Message: &waWeb.WebMessageInfo{
			Key: &waCommon.MessageKey{ID: proto.String("creation"), RemoteJID: &group, FromMe: proto.Bool(true)}, MessageTimestamp: proto.Uint64(uint64(at.Unix())), MessageStubType: waWeb.WebMessageInfo_GROUP_CREATE.Enum(), MessageStubParameters: []string{"Grup Member"},
		}}}},
		{ID: proto.String("0@c.us"), Name: proto.String("WhatsApp Business"), Messages: []*waHistorySync.HistorySyncMsg{{Message: &waWeb.WebMessageInfo{
			Key: &waCommon.MessageKey{ID: proto.String("announcement"), RemoteJID: proto.String("0@c.us"), FromMe: proto.Bool(false)}, MessageTimestamp: proto.Uint64(uint64(at.Add(-time.Hour).Unix())), Message: &waE2E.Message{Conversation: proto.String("Kabar WhatsApp Business")},
		}}}},
		{ID: proto.String("status@broadcast"), ConversationTimestamp: proto.Uint64(uint64(at.Unix()))},
	}}})
	if len(messages) != 2 || len(states) != 2 {
		t.Fatalf("missing threads: messages=%+v states=%+v", messages, states)
	}
	if messages[0].MediaType != "system" || messages[0].Text != "Anda membuat grup \"Grup Member\"" || messages[1].Sender != "0" {
		t.Fatalf("wrong identity/content: %+v", messages)
	}
	if !states[0].Timestamp.Equal(at) || states[0].Name != "Grup Member" || !states[1].Timestamp.Equal(at.Add(-time.Hour)) {
		t.Fatalf("missing activity metadata: %+v", states)
	}
}

func TestInboxServiceIdentityDoesNotRelaxPhoneValidation(t *testing.T) {
	for _, input := range []string{"0", "0@s.whatsapp.net", "0@c.us"} {
		if NormalizeInboxSender(input) != "0" {
			t.Fatal("PSA became a phone", input)
		}
		jid, err := recipientJID(input)
		if err != nil || jid != types.PSAJID {
			t.Fatal("wrong service address", jid, err)
		}
	}
	for _, input := range []string{"62", "123", "status@broadcast", "123@lid"} {
		if NormalizeInboxSender(input) != "" {
			t.Fatal("invalid identity accepted", input)
		}
	}
	if valid, _ := ValidatePhoneForWA("0"); valid {
		t.Fatal("PSA accepted as a customer phone")
	}
}

func TestInboxServiceLiveMessageNeverEntersAI(t *testing.T) {
	oldSync, oldMessage := onHistorySync, onMessage
	t.Cleanup(func() { onHistorySync, onMessage = oldSync, oldMessage })
	var got []HistoricalMessage
	onHistorySync = func(_ uint, m []HistoricalMessage) (int, int, error) { got = append(got, m...); return len(m), 0, nil }
	onMessage = func(_ uint, _ types.JID, _ IncomingMessage) { t.Error("official announcement entered AI") }
	w := &waInstance{}
	w.handleEvent(&events.Message{Info: types.MessageInfo{ID: "live-psa", Timestamp: time.Now(), MessageSource: types.MessageSource{Chat: types.PSAJID, Sender: types.PSAJID}}, Message: &waE2E.Message{Conversation: proto.String("Kabar resmi")}})
	if len(got) != 1 || got[0].Sender != "0" {
		t.Fatalf("announcement missing: %+v", got)
	}
}

func TestInboxActivityUsesNewestValidWhatsAppTimestamp(t *testing.T) {
	at := time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC)
	conv := &waHistorySync.Conversation{LastMsgTimestamp: proto.Uint64(uint64(at.Add(-24 * time.Hour).Unix())), ConversationTimestamp: proto.Uint64(uint64(at.Unix()))}
	if !historyConversationTime(conv).Equal(at) {
		t.Fatal("used old local tip")
	}
	if _, ok := historicalSystemActivity(&waWeb.WebMessageInfo{Key: &waCommon.MessageKey{ID: proto.String("encryption")}, MessageTimestamp: proto.Uint64(uint64(at.Unix())), MessageStubType: waWeb.WebMessageInfo_E2E_ENCRYPTED.Enum()}, "628111111111"); ok {
		t.Fatal("encryption notice imported")
	}
}
