package com.rugvedsarika.privatelog.data.database

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.rugvedsarika.privatelog.data.dao.NoteDao
import com.rugvedsarika.privatelog.data.model.Note
import com.rugvedsarika.privatelog.utils.PreferenceHelper
import net.sqlcipher.database.SupportFactory

@Database(entities = [Note::class], version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {

    abstract fun noteDao(): NoteDao

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

        fun getDatabase(context: Context): AppDatabase {
            return INSTANCE ?: synchronized(this) {
                val prefs = PreferenceHelper(context)
                val passphrase = prefs.getOrGenerateDatabaseKey()
                val factory = SupportFactory(passphrase)

                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    AppDatabase::class.java,
                    "privatelog_db"
                )
                .openHelperFactory(factory)
                .addCallback(object : RoomDatabase.Callback() {
                    override fun onCreate(db: androidx.sqlite.db.SupportSQLiteDatabase) {
                        super.onCreate(db)
                        // Using a thread to insert dummy data since we can't do it on main thread
                        // and we don't have a coroutine scope handy here easily without more refactoring.
                        // Ideally use a CoroutineScope injected or Application scope.
                        // Check if we can use a simple thread for this one-off.
                        Thread {
                            val dao = getDatabase(context).noteDao()
                            val now = System.currentTimeMillis()
                            kotlinx.coroutines.runBlocking {
                                dao.insert(Note(title = "Welcome to PrivateLog", content = "This is your secure space. Your notes are encrypted safely.", timestamp = now))
                                dao.insert(Note(title = "Features", content = "- AES-256 Encryption\n- Biometric Unlock\n- Offline Search\n- Backup & Restore", timestamp = now))
                                dao.insert(Note(title = "Ideas", content = "Start writing your next big idea here...", timestamp = now, category = "Ideas"))
                            }
                        }.start()
                    }
                })
                .build()
                
                INSTANCE = instance
                instance
            }
        }
    }
}
