package com.zyzf.coffeepreorder.database.dao

import androidx.paging.PagingSource
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update
import com.zyzf.coffeepreorder.database.model.Cart
import com.zyzf.coffeepreorder.database.model.Coffee

@Dao
interface CartDao {
    @Query("select * from cart")
    suspend fun getAll(): Cart

    @Query("select coffee.uid, coffee.name, coffee.cost, coffee.ingredients from cart join coffee on coffee.uid = cart.coffee_id and cart.count > 0 collate nocase")
    fun getAllInCart(): PagingSource<Int, Coffee>

    @Query("select sum(coffee.cost * cart.count) from cart JOIN coffee on coffee.uid = cart.coffee_id and cart.count > 0")
    fun getSumInCart(): Double

    @Query("select cart.count from cart JOIN coffee on coffee.uid = cart.coffee_id where coffee.uid = :coffeeId")
    fun getCountForCoffee(coffeeId: Int): Double

    @Insert
    suspend fun insert(cart: Cart)

    @Query("select * from cart where coffee_id = :coffeeId limit 1")
    suspend fun findCoffee(coffeeId: Int): Cart?
    @Query("insert into cart (coffee_id, count) values (:coffeeId, :count)")
    suspend fun insertNewCoffee(coffeeId: Int, count: Int)
    @Query("update cart set count = count + :count where coffee_id = :coffeeId")
    suspend fun updateExistingCoffee(coffeeId: Int, count: Int)
    @Transaction
    suspend fun insertCoffee(coffeeId: Int, count: Int) {
        val cart: Cart? = findCoffee(coffeeId)
        if (cart != null) {
            updateExistingCoffee(coffeeId, count)
        } else {
            insertNewCoffee(coffeeId, count)
        }
    }

    @Query("update cart set count = count - :count where coffee_id = :coffeeId")
    suspend fun deleteCoffee(coffeeId: Int, count: Int)

    @Update
    suspend fun update(cart: Cart)

    @Query("delete from cart")
    suspend fun deleteAll()
}