package ru.fincode.tsudesk.core.database.api.schedule

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import kotlinx.coroutines.flow.Flow
import ru.fincode.tsudesk.core.database.api.schedule.Query.DELETE_LESSON_BY_KEY_QUERY
import ru.fincode.tsudesk.core.database.api.schedule.Query.DELETE_SCHEDULE_BY_KEY_QUERY
import ru.fincode.tsudesk.core.database.api.schedule.Query.SELECT_LESSON_BY_KEY_QUERY
import ru.fincode.tsudesk.core.database.api.schedule.Query.SELECT_SCHEDULE_BY_KEY_QUERY

@Dao
interface ScheduleDao {

    @Query(SELECT_SCHEDULE_BY_KEY_QUERY)
    fun observeSchedule(key: String): Flow<ScheduleCacheEntity?>

    @Query(SELECT_LESSON_BY_KEY_QUERY)
    fun observeLessons(key: String): Flow<List<LessonCacheEntity>>

    @Query(SELECT_SCHEDULE_BY_KEY_QUERY)
    suspend fun getSchedule(key: String): ScheduleCacheEntity?

    @Query(SELECT_LESSON_BY_KEY_QUERY)
    suspend fun getLessons(key: String): List<LessonCacheEntity>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun upsertSchedule(schedule: ScheduleCacheEntity)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertLessons(lessons: List<LessonCacheEntity>)

    @Query(DELETE_LESSON_BY_KEY_QUERY)
    suspend fun deleteLessonsByKey(key: String)

    @Query(DELETE_SCHEDULE_BY_KEY_QUERY)
    suspend fun deleteScheduleByKey(key: String)

    @Transaction
    suspend fun replaceSchedule(
        key: String,
        schedule: ScheduleCacheEntity,
        lessons: List<LessonCacheEntity>
    ) {
        deleteLessonsByKey(key)
        upsertSchedule(schedule)
        insertLessons(lessons)
    }

    @Transaction
    suspend fun clearSchedule(key: String) {
        deleteLessonsByKey(key)
        deleteScheduleByKey(key)
    }
}