package ru.forbion.f7cloud.core.database

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

@Dao
interface ContactsDao {
    @Query(
        """
        SELECT * FROM contacts
        WHERE accountKey = :accountKey
        ORDER BY displayName COLLATE NOCASE
        """,
    )
    fun observeAll(accountKey: String): Flow<List<ContactEntity>>

    @Query(
        """
        SELECT * FROM contacts
        WHERE accountKey = :accountKey
        ORDER BY displayName COLLATE NOCASE
        """,
    )
    suspend fun getAll(accountKey: String): List<ContactEntity>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertAll(contacts: List<ContactEntity>)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(contact: ContactEntity)

    @Query("DELETE FROM contacts WHERE accountKey = :accountKey")
    suspend fun deleteAll(accountKey: String)

    @Transaction
    suspend fun replaceAll(accountKey: String, contacts: List<ContactEntity>) {
        deleteAll(accountKey)
        if (contacts.isNotEmpty()) {
            insertAll(contacts)
        }
    }
}
