package com.applemand.zmanim.core.location

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton

/**
 * Read-only database populated from `assets/databases/cities.db`, which is generated
 * at build time from GeoNames cities500 + Hebcal Hebrew aliases via
 * `tools/build_cities_db.py` (see core/location/README.md).
 */
@Database(
    entities = [CityEntity::class, CityFtsEntity::class],
    version = 1,
    exportSchema = true,
)
abstract class CitiesDatabase : RoomDatabase() {
    abstract fun cityDao(): CityDao
}

@Module
@InstallIn(SingletonComponent::class)
object CitiesDatabaseModule {
    @Provides
    @Singleton
    fun provideCitiesDatabase(@ApplicationContext context: Context): CitiesDatabase =
        Room.databaseBuilder(context, CitiesDatabase::class.java, "cities.db")
            .createFromAsset("databases/cities.db")
            .fallbackToDestructiveMigrationOnDowngrade()
            .build()

    @Provides
    fun provideCityDao(db: CitiesDatabase): CityDao = db.cityDao()
}
