package com.aistudio.bonjuteri.jwlry.data import android.content.Context import android.util.Log import com.google.firebase.Timestamp import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.tasks.await class FavoriteRepository( private val firestore: FirebaseFirestore, private val auth: FirebaseAuth ) { companion object { private const val TAG = "FavoriteRepository" @Volatile private var INSTANCE: FavoriteRepository? = null fun getInstance(context: Context): FavoriteRepository { return INSTANCE ?: synchronized(this) { INSTANCE ?: FavoriteRepository( FirestoreHelper.getFirestore(context), FirebaseAuth.getInstance() ).also { INSTANCE = it } } } } private fun requireUserId(): String { return auth.currentUser?.uid ?: throw IllegalStateException("Favori işlemleri için lütfen giriş yapınız.") } fun observeFavoriteProductIds(): Flow> = callbackFlow { val uid = auth.currentUser?.uid if (uid == null) { trySend(emptySet()) close() return@callbackFlow } val favRef = firestore.collection("users").document(uid).collection("favorites") val listener = favRef.addSnapshotListener { snapshot, error -> if (error != null) { FirestoreHelper.handleFirestoreError(error, "observeFavoriteProductIds", favRef.path) trySend(emptySet()) return@addSnapshotListener } val ids = snapshot?.documents?.map { it.id }?.toSet() ?: emptySet() trySend(ids) } awaitClose { listener.remove() } } suspend fun toggleFavorite(productId: String): Result { return try { val uid = requireUserId() val docRef = firestore.collection("users").document(uid) .collection("favorites").document(productId) val snapshot = docRef.get().await() val isNowFavorite = if (snapshot.exists()) { docRef.delete().await() false } else { docRef.set(mapOf("productId" to productId, "addedAt" to Timestamp.now())).await() true } Result.success(isNowFavorite) } catch (e: Throwable) { Log.e(TAG, "Favori değiştirme hatası: ${e.message}", e) Result.failure(Exception(e.localizedMessage ?: "Favori işlemi başarısız.")) } } }