// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package services

import (
	"context"
	"maps"
	"strings"
	"time"

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

type savedContactCache struct {
	client  *whatsmeow.Client
	names   map[string]string
	expires time.Time
}

func savedContactName(info types.ContactInfo) string {
	for _, value := range []string{info.FullName, info.FirstName} {
		if name := strings.TrimSpace(value); name != "" {
			return name
		}
	}
	return ""
}

func (w *waInstance) invalidateContactNames() {
	w.contactNamesMu.Lock()
	w.contactNamesCache = savedContactCache{}
	w.contactNamesMu.Unlock()
}

// CachedContactNames returns only names saved in this WhatsApp account's address
// book. Push/business/CRM names are not evidence that a number is a saved contact.
// Concurrent operators share one local-store read; callers get their own map.
func (w *waInstance) CachedContactNames(ctx context.Context) (map[string]string, error) {
	w.contactNamesMu.Lock()
	defer w.contactNamesMu.Unlock()
	w.mu.Lock()
	client := w.client
	w.mu.Unlock()
	if client == nil || client.Store == nil || client.Store.Contacts == nil {
		return nil, nil
	}
	if w.contactNamesCache.client == client && time.Now().Before(w.contactNamesCache.expires) {
		return maps.Clone(w.contactNamesCache.names), nil
	}
	ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
	defer cancel()
	all, err := client.Store.Contacts.GetAllContacts(ctx)
	if err != nil {
		return nil, err
	}
	byNumber := make(map[string]string, len(all))
	// Phone entries are authoritative; LID aliases only fill a missing name.
	for jid, info := range all {
		if jid.Server == types.DefaultUserServer && jid.User != "" {
			if name := savedContactName(info); name != "" {
				byNumber[jid.User] = name
			}
		}
	}
	for jid, info := range all {
		name := savedContactName(info)
		if name == "" || jid.Server != types.HiddenUserServer || client.Store.LIDs == nil {
			continue
		}
		pn, err := client.Store.LIDs.GetPNForLID(ctx, jid)
		if err == nil && pn.Server == types.DefaultUserServer && pn.User != "" && byNumber[pn.User] == "" {
			byNumber[pn.User] = name
		}
	}
	if err := ctx.Err(); err != nil {
		return nil, err
	}
	w.contactNamesCache = savedContactCache{client: client, names: byNumber, expires: time.Now().Add(2 * time.Minute)}
	return maps.Clone(byNumber), nil
}
