package services

import (
	"context"

	"github.com/treytartt/honeydue-api/internal/repositories"
)

// cachedResidenceIDsForUser fetches the residence-ID list for a user, going
// through Redis (5-min TTL) before falling back to Postgres.
//
// Used on every authed read path (tasks, documents, contractors, summary)
// because the list rarely changes — only on share-code accept, member
// removal, or residence delete. Callers must invalidate after mutations
// via cache.InvalidateResidenceIDsForUsers.
//
// A nil cache is permitted — the function falls through to the repo
// directly, so this works in tests and in failure modes.
func cachedResidenceIDsForUser(
	ctx context.Context,
	cache *CacheService,
	residenceRepo *repositories.ResidenceRepository,
	userID uint,
) ([]uint, error) {
	if cache != nil {
		if ids, err := cache.GetCachedResidenceIDsForUser(ctx, userID); err == nil {
			return ids, nil
		}
	}

	ids, err := residenceRepo.WithContext(ctx).FindResidenceIDsByUser(userID)
	if err != nil {
		return nil, err
	}

	if cache != nil {
		// Best-effort cache fill; don't fail the request on Redis hiccup.
		_ = cache.CacheResidenceIDsForUser(ctx, userID, ids)
	}
	return ids, nil
}
