package com.aistudio.bonjuteri.jwlry.data import android.content.Context import android.util.Log import com.aistudio.bonjuteri.jwlry.model.Banner 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 BannerRepository( private val firestore: FirebaseFirestore ) { companion object { private const val TAG = "BannerRepository" const val BANNERS_COLLECTION = "banners" @Volatile private var INSTANCE: BannerRepository? = null fun getInstance(context: Context): BannerRepository { return INSTANCE ?: synchronized(this) { INSTANCE ?: BannerRepository( FirestoreHelper.getFirestore(context) ).also { INSTANCE = it } } } } fun observeBanners(onlyActive: Boolean = true): Flow> = callbackFlow { val query = if (onlyActive) { firestore.collection(BANNERS_COLLECTION).whereEqualTo("isActive", true) } else { firestore.collection(BANNERS_COLLECTION) } val listener = query.addSnapshotListener { snapshot, error -> if (error != null) { FirestoreHelper.handleFirestoreError(error, "observeBanners", BANNERS_COLLECTION) trySend(emptyList()) return@addSnapshotListener } val list = snapshot?.documents?.mapNotNull { it.toObject(Banner::class.java) } ?.sortedBy { it.order } ?: emptyList() trySend(list) } awaitClose { listener.remove() } } suspend fun addBanner( title: String, subtitle: String, imageUrl: String, linkTarget: String, order: Long ): Result { val trimmedTitle = title.trim() val trimmedImg = imageUrl.trim() if (trimmedTitle.isBlank()) { return Result.failure(IllegalArgumentException("Banner başlığı boş olamaz.")) } if (trimmedImg.isBlank()) { return Result.failure(IllegalArgumentException("Banner görsel URL'si boş olamaz.")) } return try { val docRef = firestore.collection(BANNERS_COLLECTION).document() val banner = Banner( id = docRef.id, title = trimmedTitle, subtitle = subtitle.trim(), imageUrl = trimmedImg, linkTarget = linkTarget.trim(), order = order, isActive = true ) docRef.set(banner).await() Result.success(banner) } catch (e: Throwable) { val msg = FirestoreHelper.handleFirestoreError(e, "addBanner", BANNERS_COLLECTION) Result.failure(Exception(msg)) } } suspend fun updateBanner(banner: Banner): Result { return try { firestore.collection(BANNERS_COLLECTION).document(banner.id).set(banner).await() Result.success(banner) } catch (e: Throwable) { val msg = FirestoreHelper.handleFirestoreError(e, "updateBanner", banner.id) Result.failure(Exception(msg)) } } suspend fun deleteBanner(bannerId: String): Result { return try { firestore.collection(BANNERS_COLLECTION).document(bannerId).delete().await() Result.success(Unit) } catch (e: Throwable) { val msg = FirestoreHelper.handleFirestoreError(e, "deleteBanner", bannerId) Result.failure(Exception(msg)) } } }