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

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

@Dao
interface RecentReadDao {
    
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertOrUpdate(recentRead: RecentReadEntity)
    
    @Query("SELECT * FROM recently_read WHERE filePath = :filePath")
    suspend fun getByFilePath(filePath: String): RecentReadEntity?
    
    @Query("""
        SELECT pdf_documents.* 
        FROM pdf_documents 
        INNER JOIN recently_read ON pdf_documents.filePath = recently_read.filePath 
        ORDER BY recently_read.lastOpenedTime DESC
    """)
    fun getRecentReadDocuments(): Flow<List<PdfDocumentEntity>>
    
    @Query("UPDATE recently_read SET lastOpenedTime = :time, openedCount = openedCount + 1 WHERE filePath = :filePath")
    suspend fun updateOpenTime(filePath: String, time: Long = System.currentTimeMillis())
    
    @Query("UPDATE recently_read SET totalReadTime = totalReadTime + :additionalTime WHERE filePath = :filePath")
    suspend fun addReadTime(filePath: String, additionalTime: Long)
    
    @Query("DELETE FROM recently_read WHERE filePath = :filePath")
    suspend fun deleteByPdfPath(filePath: String)

    @Query("DELETE FROM recently_read WHERE filePath IN (:filePaths)")
    suspend fun deleteByPdfPaths(filePaths: List<String>)


    @Query("DELETE FROM recently_read WHERE lastOpenedTime < :cutoffTime")
    suspend fun deleteOldRecents(cutoffTime: Long)
}