package com.durian.tssparty.data.local

import androidx.room.*
import kotlinx.coroutines.flow.Flow

/**
 * Entity for storing TSS share records
 */
@Entity(tableName = "share_records")
data class ShareRecordEntity(
    @PrimaryKey(autoGenerate = true)
    val id: Long = 0,

    @ColumnInfo(name = "session_id")
    val sessionId: String,

    @ColumnInfo(name = "public_key")
    val publicKey: String,

    @ColumnInfo(name = "encrypted_share")
    val encryptedShare: String,

    @ColumnInfo(name = "threshold_t")
    val thresholdT: Int,

    @ColumnInfo(name = "threshold_n")
    val thresholdN: Int,

    @ColumnInfo(name = "party_index")
    val partyIndex: Int,

    @ColumnInfo(name = "address")
    val address: String,

    @ColumnInfo(name = "created_at")
    val createdAt: Long = System.currentTimeMillis()
)

/**
 * DAO for share records
 */
@Dao
interface ShareRecordDao {
    @Query("SELECT * FROM share_records ORDER BY created_at DESC")
    fun getAllShares(): Flow<List<ShareRecordEntity>>

    @Query("SELECT * FROM share_records WHERE id = :id")
    suspend fun getShareById(id: Long): ShareRecordEntity?

    @Query("SELECT * FROM share_records WHERE session_id = :sessionId")
    suspend fun getShareBySessionId(sessionId: String): ShareRecordEntity?

    @Query("SELECT * FROM share_records WHERE address = :address")
    suspend fun getShareByAddress(address: String): ShareRecordEntity?

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertShare(share: ShareRecordEntity): Long

    @Delete
    suspend fun deleteShare(share: ShareRecordEntity)

    @Query("DELETE FROM share_records WHERE id = :id")
    suspend fun deleteShareById(id: Long)

    @Query("SELECT COUNT(*) FROM share_records")
    suspend fun getShareCount(): Int
}

/**
 * Entity for storing app settings (like persistent partyId)
 */
@Entity(tableName = "app_settings")
data class AppSettingEntity(
    @PrimaryKey
    val key: String,

    @ColumnInfo(name = "value")
    val value: String
)

/**
 * DAO for app settings
 */
@Dao
interface AppSettingDao {
    @Query("SELECT value FROM app_settings WHERE `key` = :key")
    suspend fun getValue(key: String): String?

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun setValue(setting: AppSettingEntity)
}

/**
 * Room database
 */
@Database(
    entities = [ShareRecordEntity::class, AppSettingEntity::class],
    version = 2,
    exportSchema = false
)
abstract class TssDatabase : RoomDatabase() {
    abstract fun shareRecordDao(): ShareRecordDao
    abstract fun appSettingDao(): AppSettingDao
}
