package com.laseroptek.raman.data.datasource.db

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.laseroptek.raman.const.DATABASE_VERSION
import com.laseroptek.raman.data.source.db.dao.SerialLogDao
import com.laseroptek.raman.data.source.db.model.SerialLog

/**
 * The [RoomDatabase] we use in this app.
 */
@Database(entities = [SerialLog::class], version = DATABASE_VERSION, exportSchema = false)
abstract class RamanDatabase : RoomDatabase() {
    abstract fun serialLogDao(): SerialLogDao
    companion object {
        const val DATABASE_NAME = "raman.db"

        // Optional: Singleton pattern if not using Hilt (Hilt handles this better)
        @Volatile
        private var INSTANCE: RamanDatabase? = null

        fun getInstance(context: Context): RamanDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    RamanDatabase::class.java,
                    DATABASE_NAME
                )
                    // Add migrations here if DATABASE_VERSION increases
                    // .addMigrations(MIGRATION_1_2, MIGRATION_2_3)
                    .fallbackToDestructiveMigration(dropAllTables = true) // Use with caution, deletes data on schema change if no migration
                    .build()
                INSTANCE = instance
                instance
            }
        }
    }
}