package com.example.oscellamobile

import androidx.compose.runtime.Composable
import androidx.lifecycle.ViewModel
import androidx.navigation.NavController
import com.example.oscellamobile.domain.utlis.Constant.supabase
import com.example.oscellamobile.models.Favorite
import com.example.oscellamobile.models.Game
import io.github.jan.supabase.postgrest.from
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class Favourites(): ViewModel() {
    suspend fun addToFavorites(id_game: Int, id_user: Int, navController: NavController, fav: Int?, screen: String) {
        val newFav = Favorite(
            id_game = id_game,
            id_user = id_user
        )

        val newFavouritesCount = fav?.plus(1) ?: 1

        val response = supabase.from("Game").update(
            {
                Game::favourites setTo newFavouritesCount
                set("favourites", newFavouritesCount)
            }
        ) {
            filter {
                Game::id eq id_game
            }
        }

        withContext(Dispatchers.IO) {
            supabase.from("Favorite").insert(newFav)
        }
        navController.navigate(screen)
    }

    suspend fun removeFromFavorites(id_game: Int, id_user: Int, navController: NavController, fav: Int?, screen: String) {
        withContext(Dispatchers.IO) {

            val newFavouritesCount = fav?.minus(1) ?: 1

            supabase.from("Game").update(
                {
                    Game::favourites setTo newFavouritesCount
                    set("favourites", newFavouritesCount)
                }
            ) {
                filter {
                    Game::id eq id_game
                }
            }

            val response = supabase.from("Favorite").delete {
                filter {
                    (Favorite::id_game eq id_game)
                    (Favorite::id_user eq id_user)
                }
            }
        }
        navController.navigate(screen)
    }
}