package com.syncflow.data.db

import androidx.room.*
import com.syncflow.data.db.entities.SyncPairEntity
import com.syncflow.domain.model.SyncStatus
import kotlinx.coroutines.flow.Flow
import java.time.Instant

@Dao
interface SyncPairDao {
    @Query("SELECT * FROM sync_pairs ORDER BY name")
    fun observeAll(): Flow<List<SyncPairEntity>>

    @Query("SELECT * FROM sync_pairs WHERE isEnabled = 1")
    suspend fun getEnabled(): List<SyncPairEntity>

    @Query("SELECT * FROM sync_pairs WHERE id = :id")
    suspend fun getById(id: Long): SyncPairEntity?

    @Query("SELECT * FROM sync_pairs WHERE id = :id")
    fun observeById(id: Long): Flow<SyncPairEntity?>

    @Insert(onConflict = OnConflictStrategy.ABORT)
    suspend fun insert(entity: SyncPairEntity): Long

    @Update
    suspend fun update(entity: SyncPairEntity)

    @Delete
    suspend fun delete(entity: SyncPairEntity)

    @Query("UPDATE sync_pairs SET lastSyncAt = :at, lastSyncResult = :result, pendingConflicts = :conflicts, lastSyncUploaded = :uploaded, lastSyncDownloaded = :downloaded, lastSyncDeleted = :deleted, lastSyncBytesTransferred = :bytes WHERE id = :id")
    suspend fun updateSyncResult(id: Long, at: Instant, result: SyncStatus, conflicts: Int, uploaded: Int, downloaded: Int, deleted: Int, bytes: Long)

    @Query("UPDATE sync_pairs SET lastSyncResult = :status WHERE id = :id")
    suspend fun updateStatus(id: Long, status: SyncStatus)
}
