package de.krisenvorrat.app.data.db.dao

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import androidx.room.Upsert
import de.krisenvorrat.app.data.db.entity.ItemEntity
import kotlinx.coroutines.flow.Flow
import java.time.LocalDate

@Dao
internal interface ItemDao {

    @Insert
    suspend fun insert(item: ItemEntity)

    @Update
    suspend fun update(item: ItemEntity)

    @Delete
    suspend fun delete(item: ItemEntity)

    @Query("SELECT * FROM items")
    fun getAll(): Flow<List<ItemEntity>>

    @Query("SELECT * FROM items WHERE id = :id")
    suspend fun getById(id: String): ItemEntity?

    @Query("SELECT * FROM items WHERE category_id = :categoryId")
    fun getByCategory(categoryId: Int): Flow<List<ItemEntity>>

    @Query("SELECT * FROM items WHERE location_id = :locationId")
    fun getByLocation(locationId: Int): Flow<List<ItemEntity>>

    @Query("SELECT * FROM items WHERE expiry_date IS NOT NULL AND expiry_date <= :cutoff")
    fun getExpiringSoonByCutoff(cutoff: LocalDate): Flow<List<ItemEntity>>

    @Upsert
    suspend fun upsertAll(items: List<ItemEntity>)

    @Query("SELECT COUNT(*) FROM items WHERE category_id = :categoryId")
    suspend fun countByCategoryId(categoryId: Int): Int

    @Query("UPDATE items SET category_id = :toId WHERE category_id = :fromId")
    suspend fun updateCategoryId(fromId: Int, toId: Int)

    @Query("SELECT COUNT(*) FROM items WHERE location_id = :locationId")
    suspend fun countByLocationId(locationId: Int): Int

    @Query("UPDATE items SET location_id = :toId WHERE location_id = :fromId")
    suspend fun updateLocationId(fromId: Int, toId: Int)

    @Query("SELECT location_id FROM items ORDER BY last_updated DESC LIMIT 1")
    suspend fun getLastUsedLocationId(): Int?
}
