package com.example.tabbuy.data.local

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.example.tabbuy.data.local.dao.KeranjangDao
import com.example.tabbuy.data.local.dao.PelangganDao
import com.example.tabbuy.data.local.dao.ProdukDao
import com.example.tabbuy.data.local.entity.KeranjangEntity
import com.example.tabbuy.data.local.entity.PelangganEntity
import com.example.tabbuy.data.local.entity.ProdukEntity

@Database(
    entities = [ProdukEntity::class, KeranjangEntity::class, PelangganEntity::class],
    version = 2, // Naikkan versi ke 2 karena ada perubahan struktur
    exportSchema = false
)
abstract class AppDatabase : RoomDatabase() {
    abstract fun produkDao(): ProdukDao
    abstract fun pelangganDao(): PelangganDao
    abstract fun keranjangDao(): KeranjangDao

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

        fun getDatabase(context: Context): AppDatabase {
            return instance ?: synchronized(this) {
                val newInstance = Room.databaseBuilder(
                    context.applicationContext,
                    AppDatabase::class.java,
                    "tabbuy_database"
                )
                .fallbackToDestructiveMigration() // Menghapus DB lama jika versi naik (mencegah crash)
                .build()
                instance = newInstance
                newInstance
            }
        }
    }
}
