package services

import (
	"context"
	"sync"
	"sync/atomic"
	"testing"

	"go.mau.fi/whatsmeow"
	"go.mau.fi/whatsmeow/store"
	"go.mau.fi/whatsmeow/types"
)

type savedContactTestStore struct {
	store.ContactStore
	reads atomic.Int32
	rows  map[types.JID]types.ContactInfo
}

func (s *savedContactTestStore) GetAllContacts(context.Context) (map[types.JID]types.ContactInfo, error) {
	s.reads.Add(1)
	return s.rows, nil
}

func TestSavedContactNamesExcludeProfileAndCoalesceConcurrentReads(t *testing.T) {
	s := &savedContactTestStore{rows: map[types.JID]types.ContactInfo{
		types.NewJID("628111", types.DefaultUserServer): {FullName: "  Kontak Tersimpan  ", PushName: "Profil"},
		types.NewJID("628222", types.DefaultUserServer): {PushName: "Profil asing", BusinessName: "Bisnis"},
		types.NewJID("628333", types.DefaultUserServer): {FirstName: "Nama pendek"},
		types.NewJID("1234", types.HiddenUserServer):    {FullName: "LID bukan nomor"},
	}}
	w := &waInstance{client: &whatsmeow.Client{Store: &store.Device{Contacts: s}}}
	var wg sync.WaitGroup
	for range 32 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			names, err := w.CachedContactNames(context.Background())
			if err != nil || names["628111"] != "Kontak Tersimpan" || names["628333"] != "Nama pendek" || len(names) != 2 {
				t.Errorf("saved contacts mismatch: %v %v", names, err)
			}
			names["628111"] = "Caller edit must not change shared cache"
		}()
	}
	wg.Wait()
	if s.reads.Load() != 1 {
		t.Fatalf("concurrent readers performed %d store scans", s.reads.Load())
	}
	w.invalidateContactNames()
	_, _ = w.CachedContactNames(context.Background())
	if s.reads.Load() != 2 {
		t.Fatal("contact update did not invalidate cache")
	}
	other, _ := (&waInstance{}).CachedContactNames(context.Background())
	if len(other) != 0 {
		t.Fatal("saved names leaked between accounts")
	}
}
