// Copyright (C) 2026 Jason M. Schwefel. All Rights Reserved.
package com.coldboreballisticsllc.scopedope.di

import android.content.Context
import androidx.room.Room
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import com.coldboreballisticsllc.scopedope.data.ammo.builtin.BuiltinAmmoDatabase
import com.coldboreballisticsllc.scopedope.data.ammo.user.UserAmmoDatabase
import javax.inject.Qualifier
import javax.inject.Singleton

@Qualifier @Retention(AnnotationRetention.BINARY) annotation class BuiltinDb
@Qualifier @Retention(AnnotationRetention.BINARY) annotation class UserDb

private val MIGRATION_1_2 = object : Migration(1, 2) {
    override fun migrate(db: SupportSQLiteDatabase) {
        db.execSQL("ALTER TABLE ammo ADD COLUMN bullet_weight_gr REAL NOT NULL DEFAULT 0.0")
    }
}

private val MIGRATION_2_3 = object : Migration(2, 3) {
    override fun migrate(db: SupportSQLiteDatabase) {
        db.execSQL("ALTER TABLE ammo ADD COLUMN mv_sensitivity_fps_per_f REAL NOT NULL DEFAULT 0.0")
        db.execSQL("ALTER TABLE ammo ADD COLUMN mv_reference_temp_f REAL NOT NULL DEFAULT 59.0")
    }
}

private val MIGRATION_3_4 = object : Migration(3, 4) {
    override fun migrate(db: SupportSQLiteDatabase) {
        db.execSQL("ALTER TABLE ammo ADD COLUMN form_factor REAL NOT NULL DEFAULT 0.0")
        db.execSQL("ALTER TABLE ammo ADD COLUMN bullet_diameter_mm REAL NOT NULL DEFAULT 0.0")
        db.execSQL("ALTER TABLE ammo ADD COLUMN bullet_length_mm REAL NOT NULL DEFAULT 0.0")
    }
}

@Module
@InstallIn(SingletonComponent::class)
object DatabaseModule {

    @Provides
    @Singleton
    @BuiltinDb
    fun provideBuiltinAmmoDatabase(@ApplicationContext ctx: Context): BuiltinAmmoDatabase =
        Room.databaseBuilder(ctx, BuiltinAmmoDatabase::class.java, "ammo_builtin.db")
            .createFromAsset("databases/ammo_builtin.db")
            // Built-in DB is replaced on version increment via destructive migration —
            // user data is never stored here, so data loss is acceptable.
            .fallbackToDestructiveMigration(dropAllTables = true)
            .build()

    @Provides
    @Singleton
    @UserDb
    fun provideUserAmmoDatabase(@ApplicationContext ctx: Context): UserAmmoDatabase =
        Room.databaseBuilder(ctx, UserAmmoDatabase::class.java, "ammo_user.db")
            // NO fallbackToDestructiveMigration — user data must be preserved.
            .addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4)
            .build()
}
