package com.all.pdfreader.pro.app.room.dao

import androidx.room.*
import com.all.pdfreader.pro.app.room.entity.BookmarkEntity
import kotlinx.coroutines.flow.Flow

@Dao
interface BookmarkDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(bookmark: BookmarkEntity): Long

    @Update
    suspend fun update(bookmark: BookmarkEntity): Int

    @Delete
    suspend fun delete(bookmark: BookmarkEntity): Int

    @Query("SELECT * FROM bookmarks WHERE id = :bookmarkId")
    suspend fun getById(bookmarkId: Long): BookmarkEntity?

    @Query("SELECT * FROM bookmarks WHERE filePath = :filePath ORDER BY pageNumber ASC, createTime ASC")
    fun getBookmarksByPdf(filePath: String): Flow<List<BookmarkEntity>>

    @Query("SELECT * FROM bookmarks WHERE filePath = :filePath AND pageNumber = :pageNumber")
    suspend fun getBookmarksByPage(filePath: String, pageNumber: Int): List<BookmarkEntity>

    @Query("SELECT COUNT(*) FROM bookmarks WHERE filePath = :filePath")
    suspend fun getBookmarkCount(filePath: String): Int

    @Query("DELETE FROM bookmarks WHERE filePath = :filePath")
    suspend fun deleteAllByPdf(filePath: String): Int

    @Query("DELETE FROM bookmarks WHERE filePath IN (:filePaths)")
    suspend fun deleteAllByPdfs(filePaths: List<String>): Int

    @Query("DELETE FROM bookmarks WHERE filePath = :filePath AND pageNumber = :pageNumber")
    suspend fun deleteByPage(filePath: String, pageNumber: Int)

    @Query("UPDATE bookmarks SET filePath = :newFilePath WHERE filePath = :oldFilePath")
    suspend fun updateFilePath(oldFilePath: String, newFilePath: String)
}