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

import androidx.paging.PagingSource
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import com.example.myapplication.database.entities.model.Bike
import com.example.myapplication.database.entities.model.ItemFromBike
import kotlinx.coroutines.flow.Flow

@Dao
interface BikeDao {
    @Query("select * from bikes order by name")
    fun getAll(): PagingSource<Int, Bike>

    @Query(
        "SELECT c.*, s.uid as item_uid, s.date_time, s.weight, s.max_count-IFNULL(SUM(os.count), 0) as available_count, c.uid as bike_id " +
                "FROM bikes AS c " +
                "LEFT JOIN items AS s ON s.bike_id = c.uid " +
                "LEFT JOIN rents_items AS os ON os.item_id = s.uid " +
                "WHERE c.uid = :bikeId " +
                "GROUP BY item_uid"
    )
    fun getByUid(bikeId: Int?): Flow<Map<Bike, List<ItemFromBike>>>

    @Insert
    suspend fun insert(vararg bike: Bike)

    @Update
    suspend fun update(bike: Bike)

    @Delete
    suspend fun delete(bike: Bike)

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