package services

import (
	"context"
	"errors"
	"fmt"
	"strings"
	"testing"
	"time"

	"go.mau.fi/whatsmeow"
	"go.mau.fi/whatsmeow/appstate"
	"go.mau.fi/whatsmeow/proto/waCommon"
	"go.mau.fi/whatsmeow/proto/waE2E"
	"go.mau.fi/whatsmeow/proto/waHistorySync"
	"go.mau.fi/whatsmeow/proto/waSyncAction"
	"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"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"wa-assistant/backend/database"
	"wa-assistant/backend/models"
)

func TestInboxRecoveryRequiresVerifiedSnapshotInsteadOfSendAcknowledgement(t *testing.T) {
	w := &waInstance{}
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	sent := make(chan struct{})
	result := make(chan error, 1)
	go func() { result <- w.recoverInboxAppState(ctx, func(context.Context) error { close(sent); return nil }) }()
	<-sent
	w.completeInboxStateSync(false)
	select {
	case err := <-result:
		t.Fatalf("send or regular sync completed recovery: %v", err)
	default:
	}
	if w.InboxStateSyncStatus().State != "recovering" {
		t.Fatal("unverified recovery marked successful")
	}
	w.handleEvent(&events.AppStateSyncComplete{Name: appstate.WAPatchRegular, Recovery: true})
	select {
	case err := <-result:
		t.Fatalf("wrong collection completed recovery: %v", err)
	default:
	}
	w.handleEvent(&events.AppStateSyncComplete{Name: appstate.WAPatchRegularLow, Recovery: true})
	if err := <-result; err != nil {
		t.Fatal(err)
	}
	if w.InboxStateSyncStatus().State != "synced" {
		t.Fatal("verified recovery not recorded")
	}
}

func TestInboxRecoveryTimeoutAndCooldownDoNotPretendSuccessOrFloodPrimary(t *testing.T) {
	w := &waInstance{}
	ctx, cancel := context.WithCancel(context.Background())
	sends := 0
	err := w.recoverInboxAppState(ctx, func(context.Context) error { sends++; cancel(); return nil })
	if !errors.Is(err, context.Canceled) {
		t.Fatal("missing snapshot treated as success", err)
	}
	err = w.recoverInboxAppState(context.Background(), func(context.Context) error { sends++; return nil })
	if !errors.Is(err, errInboxRecoveryPending) || sends != 1 {
		t.Fatal("recovery was retried without cooldown", sends, err)
	}
	w.inboxRecoveryAt = time.Now().Add(-6 * time.Minute)
	err = w.recoverInboxAppState(context.Background(), func(context.Context) error {
		sends++
		w.completeInboxStateSync(true)
		return nil
	})
	if err != nil || sends != 2 {
		t.Fatal("recovery did not resume after cooldown", err)
	}
}

func TestInboxRecoveryEmptyResponseDoesNotBecomeCustomerMessage(t *testing.T) {
	oldIncoming, oldOwn := onMessage, onOwnMessage
	t.Cleanup(func() { onMessage, onOwnMessage = oldIncoming, oldOwn })
	onMessage = func(uint, types.JID, IncomingMessage) { t.Fatal("recovery invoked incoming pipeline") }
	onOwnMessage = func(uint, types.JID, IncomingMessage) { t.Fatal("recovery invoked own-message pipeline") }
	w := &waInstance{client: &whatsmeow.Client{}}
	event := &events.Message{Info: types.MessageInfo{Category: "peer", MessageSource: types.MessageSource{IsFromMe: true, Sender: types.NewJID("628111111111", types.DefaultUserServer)}}, Message: &waE2E.Message{ProtocolMessage: &waE2E.ProtocolMessage{PeerDataOperationRequestResponseMessage: &waE2E.PeerDataOperationRequestResponseMessage{PeerDataOperationRequestType: waE2E.PeerDataOperationRequestType_COMPANION_SYNCD_SNAPSHOT_FATAL_RECOVERY.Enum()}}}}
	err := w.recoverInboxAppState(context.Background(), func(context.Context) error { w.handleEvent(event); return nil })
	if !errors.Is(err, errInboxRecoveryEmpty) {
		t.Fatal("empty response not distinguished", err)
	}
	if w.InboxStateSyncStatus().State != "failed" {
		t.Fatal("empty response marked successful")
	}
	event.Info.IsFromMe = false
	if w.handleInboxRecoveryPeerResponse(event) {
		t.Fatal("untrusted sender accepted as recovery")
	}
}

func TestInboxIntegrityRecoveryAndPublicDiagnostics(t *testing.T) {
	for _, err := range []error{appstate.ErrMismatchingLTHash, appstate.ErrMismatchingPatchMAC, appstate.ErrMismatchingContentMAC, appstate.ErrMismatchingIndexMAC} {
		if !recoverableInboxStateError(fmt.Errorf("wrapper: %w", err)) {
			t.Fatal("integrity error not recognized", err)
		}
	}
	w := &waInstance{}
	for _, err := range []error{context.DeadlineExceeded, appstate.ErrKeyNotFound, errors.New("database password=secret-value"), fmt.Errorf("key=secret-value: %w", errInboxRecoveryRejected)} {
		if recoverableInboxStateError(err) {
			t.Fatal("unrelated error requested recovery", err)
		}
		w.recordInboxStateSync("failed", err)
		if strings.Contains(w.InboxStateSyncStatus().Error, "secret-value") {
			t.Fatal("diagnostics exposed raw error")
		}
	}
}

type cachedPinSettings struct {
	store.ChatSettingsStore
	rows map[types.JID]types.LocalChatSettings
}

func (s cachedPinSettings) GetChatSettings(_ context.Context, jid types.JID) (types.LocalChatSettings, error) {
	return s.rows[jid], nil
}

type cachedPinContacts struct {
	store.ContactStore
	rows map[types.JID]types.ContactInfo
}

func (s cachedPinContacts) GetAllContacts(context.Context) (map[types.JID]types.ContactInfo, error) {
	return s.rows, nil
}

func TestCachedPinsRestorePrivateChatsAndGroupsWithoutMessageHistory(t *testing.T) {
	oldDB, oldHandler := database.DB, onChatPin
	database.DB = nil
	t.Cleanup(func() { database.DB, onChatPin = oldDB, oldHandler })
	private := types.NewJID("628111111111", types.DefaultUserServer)
	group := types.NewJID("120363000000001", types.GroupServer)
	unpinned := types.NewJID("628222222222", types.DefaultUserServer)
	client := &whatsmeow.Client{Store: &store.Device{ChatSettings: cachedPinSettings{rows: map[types.JID]types.LocalChatSettings{private: {Found: true, Pinned: true}, group: {Found: true, Pinned: true}, unpinned: {Found: true}}}, Contacts: cachedPinContacts{rows: map[types.JID]types.ContactInfo{private: {}, unpinned: {}}}}}
	w := &waInstance{agentID: 3, client: client, groupNames: map[string]string{group.String(): "Grup lama"}}
	seen := map[string]bool{}
	onChatPin = func(id uint, pin ChatPinUpdate) error {
		if id != 3 || !pin.FromHistory || !pin.Pinned {
			t.Fatal("cached pins lost scope or overrode live event")
		}
		seen[pin.Sender] = true
		return nil
	}
	if err := w.restoreCachedChatPins(context.Background(), client); err != nil {
		t.Fatal(err)
	}
	if len(seen) != 2 || !seen[private.User] || !seen[group.String()] {
		t.Fatal("private or old group pin missing", seen)
	}
}

func TestPinLiveProtocolBypassesCustomerAndOwnMessagePipelines(t *testing.T) {
	oldPin, oldIncoming, oldOwn, oldGroup := onMessagePin, onMessage, onOwnMessage, onGroupMessage
	t.Cleanup(func() { onMessagePin, onMessage, onOwnMessage, onGroupMessage = oldPin, oldIncoming, oldOwn, oldGroup })
	var pins []MessagePinUpdate
	onMessagePin = func(agentID uint, pin MessagePinUpdate) error {
		if agentID != 1 {
			t.Fatal("wrong number")
		}
		pins = append(pins, pin)
		return nil
	}
	onMessage = func(uint, types.JID, IncomingMessage) { t.Error("pin invoked AI/incoming pipeline") }
	onOwnMessage = func(uint, types.JID, IncomingMessage) { t.Error("pin counted as human reply") }
	onGroupMessage = func(uint, GroupMessageMeta) { t.Error("pin created a group message") }
	w := &waInstance{agentID: 1, client: &whatsmeow.Client{}}
	now := time.Now().Truncate(time.Second)
	for _, group := range []bool{false, true} {
		jid := types.NewJID("628111111111", types.DefaultUserServer)
		if group {
			jid = types.NewJID("123456789012345", types.GroupServer)
		}
		for _, kind := range []waE2E.PinInChatMessage_Type{waE2E.PinInChatMessage_PIN_FOR_ALL, waE2E.PinInChatMessage_UNPIN_FOR_ALL} {
			w.handleEvent(&events.Message{Info: types.MessageInfo{ID: "pin-event", Timestamp: now, MessageSource: types.MessageSource{Chat: jid, Sender: jid, IsGroup: group, IsFromMe: true}}, Message: &waE2E.Message{PinInChatMessage: &waE2E.PinInChatMessage{Key: &waCommon.MessageKey{ID: proto.String("target-message"), RemoteJID: proto.String(jid.String())}, Type: kind.Enum(), SenderTimestampMS: proto.Int64(now.UnixMilli())}, MessageContextInfo: &waE2E.MessageContextInfo{MessageAddOnDurationInSecs: proto.Uint32(86400)}}})
		}
	}
	if len(pins) != 4 || !pins[0].Pinned || pins[1].Pinned || pins[1].ExpiresAt != nil || pins[0].ExpiresAt == nil || !pins[0].ExpiresAt.Equal(now.Add(24*time.Hour)) || pins[2].Sender != "123456789012345@g.us" {
		t.Fatal("live pin/unpin not preserved", pins)
	}
}

func TestGroupKeyPacketsDoNotBecomeChatBubbles(t *testing.T) {
	w := &waInstance{agentID: 1, client: &whatsmeow.Client{}}
	old := onGroupMessage
	t.Cleanup(func() { onGroupMessage = old })
	onGroupMessage = func(uint, GroupMessageMeta) { t.Error("key distribution rendered as a group message") }
	j := types.NewJID("120363000000001", types.GroupServer)
	event := &events.Message{Info: types.MessageInfo{ID: "shared-pin-action", Timestamp: time.Now(), MessageSource: types.MessageSource{Chat: j, Sender: types.NewJID("628111111111", types.DefaultUserServer), IsGroup: true}}, Message: &waE2E.Message{SenderKeyDistributionMessage: &waE2E.SenderKeyDistributionMessage{}}}
	w.handleEvent(event)
	if got := groupMessageText(event); got != "" {
		t.Fatal("protocol has display text", got)
	}
	event.Message = &waE2E.Message{Conversation: proto.String("Pesan grup")}
	if got := groupMessageText(event); got != "Pesan grup" {
		t.Fatal("real text lost", got)
	}
	event.Message = &waE2E.Message{ImageMessage: &waE2E.ImageMessage{}}
	if got := groupMessageText(event); got == "" {
		t.Fatal("captionless media hidden")
	}
}

func TestHistoryPinsReadMetadataAndAddOnsWithServerTimestamp(t *testing.T) {
	now := time.Now().Truncate(time.Second)
	jid := "628111111111@s.whatsapp.net"
	web := &waWeb.WebMessageInfo{Key: &waCommon.MessageKey{ID: proto.String("old-target"), RemoteJID: &jid}, MessageTimestamp: proto.Uint64(uint64(now.Add(-90 * 24 * time.Hour).Unix())), Message: &waE2E.Message{Conversation: proto.String("Info penting")}, PinInChat: &waWeb.PinInChat{Type: waWeb.PinInChat_PIN_FOR_ALL.Enum(), ServerTimestampMS: proto.Int64(now.UnixMilli()), SenderTimestampMS: proto.Int64(now.Add(-time.Hour).UnixMilli()), MessageAddOnContextInfo: &waWeb.MessageAddOnContextInfo{MessageAddOnDurationInSecs: proto.Uint32(604800)}}}
	pins := historyMessagePins(web, "628111111111", jid)
	if len(pins) != 1 || pins[0].MessageID != "old-target" || !pins[0].ChangedAt.Equal(now) || pins[0].ExpiresAt == nil || !pins[0].ExpiresAt.Equal(now.Add(7*24*time.Hour)) {
		t.Fatal("history metadata used original message time", pins)
	}
	web.MessageAddOns = []*waWeb.MessageAddOn{{MessageAddOnType: waWeb.MessageAddOn_PIN_IN_CHAT.Enum(), ServerTimestampMS: proto.Int64(now.Add(time.Minute).UnixMilli()), MessageAddOn: &waE2E.Message{PinInChatMessage: &waE2E.PinInChatMessage{Key: &waCommon.MessageKey{ID: proto.String("old-target")}, Type: waE2E.PinInChatMessage_UNPIN_FOR_ALL.Enum()}}}}
	pins = historyMessagePins(web, "628111111111", jid)
	if len(pins) != 2 || pins[1].Pinned || !pins[1].ChangedAt.Equal(now.Add(time.Minute)) {
		t.Fatal("unpin addon missing", pins)
	}
	web.PinInChat.Key = &waCommon.MessageKey{ID: proto.String("other"), RemoteJID: proto.String("628999999999@s.whatsapp.net")}
	web.MessageAddOns = nil
	if got := historyMessagePins(web, "628111111111", jid); len(got) != 0 {
		t.Fatal("pin from another chat accepted")
	}
}

func TestOwnPinUsesRecipientAltInsteadOfTheServiceNumber(t *testing.T) {
	old := onMessagePin
	t.Cleanup(func() { onMessagePin = old })
	var updates []MessagePinUpdate
	onMessagePin = func(_ uint, pin MessagePinUpdate) error { updates = append(updates, pin); return nil }
	now := time.Now()
	peer := types.NewJID("628111111111", types.DefaultUserServer)
	lid := types.NewJID("999888777", types.HiddenUserServer)
	self := types.NewJID("628333333333", types.DefaultUserServer)
	w := &waInstance{agentID: 1, client: &whatsmeow.Client{}}
	event := &events.Message{Info: types.MessageInfo{ID: "pin-event", Timestamp: now, MessageSource: types.MessageSource{Chat: lid, Sender: self, IsFromMe: true, RecipientAlt: peer}}, Message: &waE2E.Message{PinInChatMessage: &waE2E.PinInChatMessage{Key: &waCommon.MessageKey{ID: proto.String("target"), RemoteJID: proto.String(lid.String())}, Type: waE2E.PinInChatMessage_PIN_FOR_ALL.Enum(), SenderTimestampMS: proto.Int64(now.UnixMilli())}}}
	if !w.handleMessagePin(event) || len(updates) != 1 || updates[0].Sender != peer.User {
		t.Fatal("pin routed to service number", updates)
	}
	event.Info.RecipientAlt = types.EmptyJID
	if !w.handleMessagePin(event) || len(updates) != 1 {
		t.Fatal("unknown recipient was guessed from the sender")
	}
}

func TestHistorySyncConsumesPinActionsBeforeSystemFiltering(t *testing.T) {
	oldPin, oldHistory := onMessagePin, onHistorySync
	t.Cleanup(func() { onMessagePin, onHistorySync = oldPin, oldHistory })
	var pins []MessagePinUpdate
	onMessagePin = func(_ uint, pin MessagePinUpdate) error { pins = append(pins, pin); return nil }
	onHistorySync = func(_ uint, messages []HistoricalMessage) (int, int, error) {
		if len(messages) != 0 {
			t.Fatal("pin added as customer text")
		}
		return 0, 0, nil
	}
	j := "628111111111@s.whatsapp.net"
	now := time.Now().Truncate(time.Second)
	w := &waInstance{agentID: 1, client: &whatsmeow.Client{}}
	web := &waWeb.WebMessageInfo{Key: &waCommon.MessageKey{ID: proto.String("pin-event"), RemoteJID: &j}, MessageTimestamp: proto.Uint64(uint64(now.Unix())), Message: &waE2E.Message{PinInChatMessage: &waE2E.PinInChatMessage{Key: &waCommon.MessageKey{ID: proto.String("old-target")}, Type: waE2E.PinInChatMessage_PIN_FOR_ALL.Enum(), SenderTimestampMS: proto.Int64(now.UnixMilli())}}}
	w.processHistorySync(&events.HistorySync{Data: &waHistorySync.HistorySync{SyncType: waHistorySync.HistorySync_RECENT.Enum(), Conversations: []*waHistorySync.Conversation{{ID: &j, Messages: []*waHistorySync.HistorySyncMsg{{Message: web}}}}}})
	if len(pins) != 1 || pins[0].MessageID != "old-target" {
		t.Fatal("history pin disappeared")
	}
}

func TestHistoryPinDiagnosticsDistinguishMissingRejectedAndStoredMetadata(t *testing.T) {
	oldPin, oldHistory := onMessagePin, onHistorySync
	t.Cleanup(func() { onMessagePin, onHistorySync = oldPin, oldHistory })
	onMessagePin = func(uint, MessagePinUpdate) error { return nil }
	onHistorySync = func(uint, []HistoricalMessage) (int, int, error) { return 0, 0, nil }
	now := time.Now()
	jid := "628111111111@s.whatsapp.net"
	web := &waWeb.WebMessageInfo{Key: &waCommon.MessageKey{ID: proto.String("pin-event"), RemoteJID: &jid}, MessageTimestamp: proto.Uint64(uint64(now.Unix())), Message: &waE2E.Message{PinInChatMessage: &waE2E.PinInChatMessage{Key: &waCommon.MessageKey{ID: proto.String("target")}, Type: waE2E.PinInChatMessage_PIN_FOR_ALL.Enum()}}}
	rejected := proto.Clone(web).(*waWeb.WebMessageInfo)
	rejected.Message.PinInChatMessage.Key.RemoteJID = proto.String("628222222222@s.whatsapp.net")
	stub := &waWeb.WebMessageInfo{MessageStubType: waWeb.WebMessageInfo_PINNED_MESSAGE_IN_CHAT.Enum()}
	w := &waInstance{agentID: 1, client: &whatsmeow.Client{}}
	w.processHistorySync(&events.HistorySync{Data: &waHistorySync.HistorySync{SyncType: waHistorySync.HistorySync_ON_DEMAND.Enum(), Conversations: []*waHistorySync.Conversation{{ID: &jid, Messages: []*waHistorySync.HistorySyncMsg{{Message: web}, {Message: rejected}, {Message: stub}}}}}})
	d := w.lastHistoryResponse
	if d == nil || d.Messages != 3 || d.PinEvents != 2 || d.PinUpdates != 1 || d.PinRejected != 1 || d.PinStubs != 1 {
		t.Fatalf("incorrect pin diagnostics: %+v", d)
	}
	w.processHistorySync(&events.HistorySync{Data: &waHistorySync.HistorySync{SyncType: waHistorySync.HistorySync_ON_DEMAND.Enum(), Conversations: []*waHistorySync.Conversation{{ID: &jid}}}})
	d = w.lastHistoryResponse
	if d.PinEvents != 0 || d.PinUpdates != 0 || d.PinRejected != 0 || d.PinStubs != 0 {
		t.Fatal("a packet without pin metadata was reported as containing a pin")
	}
}

func TestChatPinEventsAndHistoryAreSeparateFromMessagePins(t *testing.T) {
	oldChat, oldMessage := onChatPin, onMessagePin
	t.Cleanup(func() { onChatPin, onMessagePin = oldChat, oldMessage })
	var updates []ChatPinUpdate
	onChatPin = func(id uint, update ChatPinUpdate) error {
		if id != 1 {
			t.Fatal("wrong agent")
		}
		updates = append(updates, update)
		return nil
	}
	onMessagePin = func(uint, MessagePinUpdate) error { t.Fatal("chat pin was treated as a message pin"); return nil }
	w := &waInstance{agentID: 1, client: &whatsmeow.Client{}}
	now := time.Now().Truncate(time.Second)
	for _, jid := range []types.JID{types.NewJID("628111111111", types.DefaultUserServer), types.NewJID("123456789", types.GroupServer)} {
		for _, pinned := range []bool{true, false} {
			w.handleEvent(&events.Pin{JID: jid, Timestamp: now, Action: &waSyncAction.PinAction{Pinned: &pinned}})
		}
	}
	w.storeHistoricalChatPin("628111111111", uint32(now.Unix()))
	w.storeHistoricalChatPin("628111111111", 0)
	if len(updates) != 5 || !updates[0].Pinned || updates[1].Pinned || updates[2].Sender != "123456789@g.us" || !updates[4].FromHistory {
		t.Fatalf("chat pin routing failed: %+v", updates)
	}
}

func TestWhatsAppPinDurationsRemainExactThroughHistoryWrappers(t *testing.T) {
	now := time.Now().Truncate(time.Second)
	for _, seconds := range []uint32{86400, 604800, 2592000} {
		t.Run((time.Duration(seconds) * time.Second).String(), func(t *testing.T) {
			inner := &waE2E.Message{PinInChatMessage: &waE2E.PinInChatMessage{Key: &waCommon.MessageKey{ID: proto.String("target")}, Type: waE2E.PinInChatMessage_PIN_FOR_ALL.Enum(), SenderTimestampMS: proto.Int64(now.UnixMilli())}}
			wrapped := &waE2E.Message{DeviceSentMessage: &waE2E.DeviceSentMessage{Message: inner}, MessageContextInfo: &waE2E.MessageContextInfo{MessageAddOnDurationInSecs: &seconds}}
			web := &waWeb.WebMessageInfo{MessageTimestamp: proto.Uint64(uint64(now.Unix())), Message: wrapped}
			pins := historyMessagePins(web, "628111111111")
			if len(pins) != 1 || pins[0].ExpiresAt == nil || !pins[0].ExpiresAt.Equal(now.Add(time.Duration(seconds)*time.Second)) {
				t.Fatalf("duration %d lost or altered: %+v", seconds, pins)
			}
			web.Message = nil
			web.MessageAddOns = []*waWeb.MessageAddOn{{MessageAddOn: wrapped}}
			pins = historyMessagePins(web, "628111111111")
			if len(pins) != 1 || pins[0].ExpiresAt == nil || !pins[0].ExpiresAt.Equal(now.Add(time.Duration(seconds)*time.Second)) {
				t.Fatalf("addon duration %d lost or altered: %+v", seconds, pins)
			}
			old := onMessagePin
			t.Cleanup(func() { onMessagePin = old })
			pins = nil
			onMessagePin = func(_ uint, update MessagePinUpdate) error { pins = append(pins, update); return nil }
			jid := types.NewJID("628111111111", types.DefaultUserServer)
			w := &waInstance{agentID: 1, client: &whatsmeow.Client{}}
			event := &events.Message{Info: types.MessageInfo{ID: "live-pin", Timestamp: now, MessageSource: types.MessageSource{Chat: jid, Sender: jid}}, Message: inner, RawMessage: wrapped}
			if !w.handleMessagePin(event) || len(pins) != 1 || pins[0].ExpiresAt == nil || !pins[0].ExpiresAt.Equal(now.Add(time.Duration(seconds)*time.Second)) {
				t.Fatalf("raw live duration %d lost or altered: %+v", seconds, pins)
			}
		})
	}
}

func TestCachedArchivesRestoreChatsWithoutMessageHistory(t *testing.T) {
	oldDB, oldHandler := database.DB, onChatArchive
	database.DB = nil
	t.Cleanup(func() { database.DB, onChatArchive = oldDB, oldHandler })
	private := types.NewJID("628111111111", types.DefaultUserServer)
	group := types.NewJID("120363000000001", types.GroupServer)
	unarchived := types.NewJID("628222222222", types.DefaultUserServer)
	client := &whatsmeow.Client{Store: &store.Device{ChatSettings: cachedPinSettings{rows: map[types.JID]types.LocalChatSettings{private: {Found: true, Archived: true}, group: {Found: true, Archived: true}, unarchived: {Found: true}}}, Contacts: cachedPinContacts{rows: map[types.JID]types.ContactInfo{private: {}, unarchived: {}}}}}
	w := &waInstance{agentID: 3, client: client, groupNames: map[string]string{group.String(): "Grup lama"}}
	seen := map[string]bool{}
	onChatArchive = func(id uint, update ChatArchiveUpdate) error {
		if id != 3 || !update.FromHistory || !update.Archived {
			t.Fatal("cached archives lost scope or overrode live event")
		}
		seen[update.Sender] = true
		return nil
	}
	if err := w.restoreCachedChatArchives(context.Background(), client); err != nil {
		t.Fatal(err)
	}
	if len(seen) != 2 || !seen[private.User] || !seen[group.String()] {
		t.Fatal("private or old group archive missing", seen)
	}
}

type cachedArchiveLIDs struct {
	store.LIDStore
	pnToLID map[types.JID]types.JID
	lidToPN map[types.JID]types.JID
}

func (s cachedArchiveLIDs) GetLIDForPN(_ context.Context, pn types.JID) (types.JID, error) {
	return s.pnToLID[pn], nil
}

func (s cachedArchiveLIDs) GetPNForLID(_ context.Context, lid types.JID) (types.JID, error) {
	return s.lidToPN[lid], nil
}

func TestCachedArchivesRestoreFromInboxStatesWithLIDSettings(t *testing.T) {
	oldDB, oldHandler := database.DB, onChatArchive
	t.Cleanup(func() { database.DB, onChatArchive = oldDB, oldHandler })
	db, err := gorm.Open(sqlite.New(sqlite.Config{DriverName: "sqlite", DSN: "file:cached-archives?mode=memory&cache=shared"}), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
	if err != nil {
		t.Fatal(err)
	}
	if err := db.AutoMigrate(&models.InboxReadState{}); err != nil {
		t.Fatal(err)
	}
	database.DB = db
	pn := types.NewJID("628111111111", types.DefaultUserServer)
	lid := types.NewJID("123456789012345", types.HiddenUserServer)
	// Thread lama: state ada, status arsip belum pernah diketahui (NULL).
	if err := db.Create(&models.InboxReadState{AgentID: 3, Sender: pn.User}).Error; err != nil {
		t.Fatal(err)
	}
	client := &whatsmeow.Client{Store: &store.Device{
		ChatSettings: cachedPinSettings{rows: map[types.JID]types.LocalChatSettings{lid: {Found: true, Archived: true}}},
		Contacts:     cachedPinContacts{rows: map[types.JID]types.ContactInfo{}},
		LIDs:         cachedArchiveLIDs{pnToLID: map[types.JID]types.JID{pn: lid}, lidToPN: map[types.JID]types.JID{lid: pn}},
	}}
	w := &waInstance{agentID: 3, client: client, groupNames: map[string]string{}}
	seen := map[string]bool{}
	onChatArchive = func(id uint, update ChatArchiveUpdate) error {
		if id != 3 || !update.FromHistory || !update.Archived {
			t.Fatal("cached archive seed lost scope", update)
		}
		seen[update.Sender] = true
		return nil
	}
	if err := w.restoreCachedChatArchives(context.Background(), client); err != nil {
		t.Fatal(err)
	}
	if !seen[pn.User] {
		t.Fatal("archived state from inbox states not restored", seen)
	}
}

func TestReconcileSeedArchivedClearsStaleSeedsOnly(t *testing.T) {
	oldDB, oldHandler := database.DB, onChatArchive
	t.Cleanup(func() { database.DB, onChatArchive = oldDB, oldHandler })
	db, err := gorm.Open(sqlite.New(sqlite.Config{DriverName: "sqlite", DSN: "file:reconcile-archives?mode=memory&cache=shared"}), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
	if err != nil {
		t.Fatal(err)
	}
	if err := db.AutoMigrate(&models.InboxReadState{}); err != nil {
		t.Fatal(err)
	}
	database.DB = db
	epoch := time.Unix(0, 0)
	liveAt := time.Date(2026, 11, 2, 9, 0, 0, 0, time.UTC)
	rows := []models.InboxReadState{
		// Seed lama yang sudah tidak ada di snapshot server: harus dibersihkan.
		{AgentID: 3, Sender: "628111111111", Archived: true, ArchiveChangedAt: &epoch},
		// Seed yang terkonfirmasi snapshot: dipertahankan (tidak dipanggil).
		{AgentID: 3, Sender: "628222222222", Archived: true, ArchiveChangedAt: &epoch},
		// Status live/aksi pengguna: tidak boleh disentuh sweep.
		{AgentID: 3, Sender: "628333333333", Archived: true, ArchiveChangedAt: &liveAt},
		// Agent lain: di luar cakupan.
		{AgentID: 4, Sender: "628111111111", Archived: true, ArchiveChangedAt: &epoch},
	}
	for _, row := range rows {
		if err := db.Create(&row).Error; err != nil {
			t.Fatal(err)
		}
	}
	w := &waInstance{agentID: 3}
	cleared := map[string]bool{}
	onChatArchive = func(id uint, update ChatArchiveUpdate) error {
		if id != 3 || !update.FromHistory || update.Archived {
			t.Fatal("sweep menyentuh status di luar seed basi", update)
		}
		cleared[update.Sender] = true
		return nil
	}
	if err := w.reconcileSeedArchived(context.Background(), map[string]bool{"628222222222": true}); err != nil {
		t.Fatal(err)
	}
	if len(cleared) != 1 || !cleared["628111111111"] {
		t.Fatal("sweep membersihkan cakupan yang salah", cleared)
	}
}
