package com.seven.ikar.kotlin.core.local

import androidx.room.Dao
import androidx.room.Entity
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.PrimaryKey
import androidx.room.Query
import kotlinx.coroutines.flow.Flow

@Entity(tableName = "transfer_queue")
data class TransferQueueEntity(
    @PrimaryKey val id: String,
    val groupId: String,
    val type: String,
    val status: String,
    val chatId: String?,
    val text: String?,
    val replyToMessageId: String?,
    val attachmentId: String?,
    val storyVisibility: String?,
    val hasProtectedContent: Boolean,
    val ttlSeconds: Int?,
    val fileName: String,
    val contentType: String,
    val fileSizeBytes: Long,
    val localPath: String,
    val sortOrder: Int,
    val progressPercent: Int,
    val errorMessage: String?,
    val createdAtMillis: Long,
    val updatedAtMillis: Long
)

@Dao
interface TransferQueueDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun upsert(items: List<TransferQueueEntity>)

    @Query("SELECT * FROM transfer_queue WHERE groupId = :groupId ORDER BY sortOrder ASC")
    suspend fun getGroup(groupId: String): List<TransferQueueEntity>

    @Query("SELECT * FROM transfer_queue WHERE chatId = :chatId AND status IN ('queued', 'running', 'failed') ORDER BY createdAtMillis ASC, sortOrder ASC")
    fun observeActiveForChat(chatId: String): Flow<List<TransferQueueEntity>>

    @Query("SELECT * FROM transfer_queue WHERE type = 'story_upload' AND status IN ('queued', 'running', 'failed') ORDER BY createdAtMillis ASC, sortOrder ASC")
    fun observeActiveStoryUploads(): Flow<List<TransferQueueEntity>>

    @Query("UPDATE transfer_queue SET status = :status, progressPercent = :progressPercent, errorMessage = :errorMessage, updatedAtMillis = :updatedAtMillis WHERE groupId = :groupId")
    suspend fun updateGroupStatus(
        groupId: String,
        status: String,
        progressPercent: Int,
        errorMessage: String?,
        updatedAtMillis: Long
    )

    @Query("DELETE FROM transfer_queue WHERE groupId = :groupId")
    suspend fun deleteGroup(groupId: String)
}

object TransferQueueTypes {
    const val Upload = "upload"
    const val StoryUpload = "story_upload"
    const val Download = "download"
}

object TransferQueueStatus {
    const val Queued = "queued"
    const val Running = "running"
    const val Completed = "completed"
    const val Failed = "failed"
}
