package com.aiosman.ravenow.data.db

import android.content.Context
import androidx.room.Dao
import androidx.room.Database
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.Upsert

@Entity(tableName = "trtc_participant_cache")
data class TrtcParticipantCache(
    @PrimaryKey val trtcId: String,
    val isAI: Boolean,
    val updatedAt: Long
)

@Dao
interface TrtcParticipantCacheDao {
    @Query("SELECT * FROM trtc_participant_cache WHERE trtcId = :trtcId LIMIT 1")
    suspend fun get(trtcId: String): TrtcParticipantCache?

    @Query("SELECT * FROM trtc_participant_cache WHERE trtcId IN (:ids)")
    suspend fun getMany(ids: List<String>): List<TrtcParticipantCache>

    @Upsert
    suspend fun upsertAll(items: List<TrtcParticipantCache>)
}

@Database(
    entities = [TrtcParticipantCache::class],
    version = 1,
    exportSchema = false
)
abstract class MessageCacheDatabase : RoomDatabase() {
    abstract fun trtcParticipantCacheDao(): TrtcParticipantCacheDao

    companion object {
        @Volatile
        private var INSTANCE: MessageCacheDatabase? = null

        fun getInstance(context: Context): MessageCacheDatabase {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: Room.databaseBuilder(
                    context.applicationContext,
                    MessageCacheDatabase::class.java,
                    "message_cache.db"
                ).fallbackToDestructiveMigration()
                    .build()
                    .also { INSTANCE = it }
            }
        }
    }
}


