package ru.forbion.f7cloud.feature.talk

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase

@Database(
    entities = [TalkRoomEntity::class, TalkMessageEntity::class],
    version = 2,
    exportSchema = false,
)
abstract class TalkOfflineDatabase : RoomDatabase() {
    abstract fun dao(): TalkOfflineDao

    companion object {
        private val MIGRATION_1_2 = object : Migration(1, 2) {
            override fun migrate(db: SupportSQLiteDatabase) {
                db.execSQL("ALTER TABLE talk_messages ADD COLUMN messageParametersJson TEXT")
            }
        }

        @Volatile
        private var INSTANCE: TalkOfflineDatabase? = null

        fun get(context: Context): TalkOfflineDatabase {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: Room.databaseBuilder(
                    context.applicationContext,
                    TalkOfflineDatabase::class.java,
                    "f7cloud-talk-offline.db",
                ).addMigrations(MIGRATION_1_2).build().also { INSTANCE = it }
            }
        }
    }
}
