package com.swoosh.microblog.data.db

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.swoosh.microblog.data.model.LocalPost

@Database(entities = [LocalPost::class], version = 4, exportSchema = false)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {

    abstract fun localPostDao(): LocalPostDao

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

        private fun addColumnsIfMissing(db: SupportSQLiteDatabase) {
            // Safely add columns - ignore if they already exist
            val columns = listOf(
                "ALTER TABLE local_posts ADD COLUMN imageAlt TEXT DEFAULT NULL",
                "ALTER TABLE local_posts ADD COLUMN featured INTEGER NOT NULL DEFAULT 0",
                "ALTER TABLE local_posts ADD COLUMN tags TEXT NOT NULL DEFAULT '[]'",
                "ALTER TABLE local_posts ADD COLUMN imageUris TEXT DEFAULT NULL",
                "ALTER TABLE local_posts ADD COLUMN uploadedImageUrls TEXT DEFAULT NULL",
                "ALTER TABLE local_posts ADD COLUMN accountId TEXT NOT NULL DEFAULT ''"
            )
            for (sql in columns) {
                try { db.execSQL(sql) } catch (_: Exception) { /* column already exists */ }
            }
        }

        val MIGRATION_1_3 = object : Migration(1, 3) {
            override fun migrate(db: SupportSQLiteDatabase) = addColumnsIfMissing(db)
        }

        val MIGRATION_2_3 = object : Migration(2, 3) {
            override fun migrate(db: SupportSQLiteDatabase) = addColumnsIfMissing(db)
        }

        val MIGRATION_3_4 = object : Migration(3, 4) {
            override fun migrate(db: SupportSQLiteDatabase) {
                val columns = listOf(
                    "ALTER TABLE local_posts ADD COLUMN emailOnly INTEGER NOT NULL DEFAULT 0",
                    "ALTER TABLE local_posts ADD COLUMN newsletterSlug TEXT DEFAULT NULL",
                    "ALTER TABLE local_posts ADD COLUMN videoUri TEXT DEFAULT NULL",
                    "ALTER TABLE local_posts ADD COLUMN uploadedVideoUrl TEXT DEFAULT NULL",
                    "ALTER TABLE local_posts ADD COLUMN audioUri TEXT DEFAULT NULL",
                    "ALTER TABLE local_posts ADD COLUMN uploadedAudioUrl TEXT DEFAULT NULL",
                    "ALTER TABLE local_posts ADD COLUMN fileUri TEXT DEFAULT NULL",
                    "ALTER TABLE local_posts ADD COLUMN uploadedFileUrl TEXT DEFAULT NULL",
                    "ALTER TABLE local_posts ADD COLUMN fileName TEXT DEFAULT NULL"
                )
                for (sql in columns) {
                    try { db.execSQL(sql) } catch (_: Exception) { }
                }
            }
        }

        fun getInstance(context: Context): AppDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    AppDatabase::class.java,
                    "swoosh_database"
                )
                    .addMigrations(MIGRATION_1_3, MIGRATION_2_3, MIGRATION_3_4)
                    .fallbackToDestructiveMigration()
                    .build()
                INSTANCE = instance
                instance
            }
        }
    }
}
