package ru.fincode.tsudesk.core.database.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.schedule.Query.DELETE_LESSONS_BY_KEY
import ru.fincode.tsudesk.core.database.schedule.Query.DELETE_SCHEDULE_BY_KEY
import ru.fincode.tsudesk.core.database.schedule.Query.SELECT_LESSONS_BY_KEY_QUERY
import ru.fincode.tsudesk.core.database.schedule.Query.SELECT_SCHEDULE_BY_KEY_QUERY


@Dao
interface ScheduleDao {

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

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

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

    @Query(SELECT_LESSONS_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_LESSONS_BY_KEY)
    suspend fun deleteLessonsByKey(key: String)

    @Query(DELETE_SCHEDULE_BY_KEY)
    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 removeSchedule(key: String) {
        deleteLessonsByKey(key)
        deleteScheduleByKey(key)
    }
}
