package com.syncflow.data.db

import androidx.room.*
import com.syncflow.data.db.entities.SyncConflictEntity
import com.syncflow.domain.model.ConflictResolution
import kotlinx.coroutines.flow.Flow

@Dao
interface SyncConflictDao {
    @Query("SELECT * FROM sync_conflicts WHERE syncPairId = :pairId AND resolution IS NULL ORDER BY detectedAt DESC")
    fun observeUnresolved(pairId: Long): Flow<List<SyncConflictEntity>>

    @Query("SELECT * FROM sync_conflicts WHERE syncPairId = :pairId ORDER BY detectedAt DESC")
    fun observeAll(pairId: Long): Flow<List<SyncConflictEntity>>

    @Query("SELECT COUNT(*) FROM sync_conflicts WHERE syncPairId = :pairId AND resolution IS NULL")
    fun observeUnresolvedCount(pairId: Long): Flow<Int>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(entity: SyncConflictEntity): Long

    @Query("UPDATE sync_conflicts SET resolution = :resolution WHERE id = :id")
    suspend fun resolve(id: Long, resolution: ConflictResolution)

    @Query("DELETE FROM sync_conflicts WHERE syncPairId = :pairId AND resolution IS NOT NULL")
    suspend fun deleteResolved(pairId: Long)
}
