package com.example.myapplication.database.entities.dao

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.example.myapplication.database.entities.model.ItemFromCart
import com.example.myapplication.database.entities.model.User
import kotlinx.coroutines.flow.Flow

@Dao
interface UserDao {
    @Query("select * from users")
    suspend fun getAll(): List<User>

    @Query("select * from users where users.uid = :idUser")
    fun getUserById(idUser: Int?): Flow<User>

    @Query(
        "SELECT items.*, items.max_count-IFNULL(SUM(rents_items.count), 0) as available_count, " +
                "users_items.count FROM items " +
                "join users_items on items.uid = users_items.item_id " +
                "left join rents_items on items.uid = rents_items.item_id " +
                "where users_items.user_id = :userId " +
                "GROUP BY users_items.item_id "
    )
    suspend fun getCartByUid(userId: Int): List<ItemFromCart>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(vararg user: User)

    @Update
    suspend fun update(user: User)

    @Delete
    suspend fun delete(user: User)

    @Query("DELETE FROM users")
    suspend fun deleteAll()
}