package com.nononsenseapps.feeder.db.room

import androidx.room.testing.MigrationTestHelper
import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.platform.app.InstrumentationRegistry
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith

@ExperimentalCoroutinesApi
@FlowPreview
@RunWith(AndroidJUnit4::class)
@LargeTest
class MigrationFrom10To11 {
    private val dbName = "testDb"

    @Rule
    @JvmField
    val testHelper: MigrationTestHelper = MigrationTestHelper(
        InstrumentationRegistry.getInstrumentation(),
        AppDatabase::class.java.canonicalName,
        FrameworkSQLiteOpenHelperFactory()
    )

    @Test
    fun migrate10to11() {
        var db = testHelper.createDatabase(dbName, 10)

        db.use {
            db.execSQL(
                """
            INSERT INTO feeds(id, title, url, custom_title, tag, notify, last_sync, response_hash)
            VALUES(1, 'feed', 'http://url', '', '', 0, 0, 666)
                """.trimIndent()
            )

            db.execSQL(
                """
            INSERT INTO feed_items(id, guid, title, plain_title, plain_snippet, unread, notified, feed_id)
            VALUES(8, 'http://item', 'title', 'ptitle', 'psnippet', 1, 0, 1)
                """.trimIndent()
            )
        }

        db = testHelper.runMigrationsAndValidate(dbName, 11, true, MIGRATION_10_11)

        db.query(
            """
            SELECT first_synced_time FROM feed_items
            """.trimIndent()
        )!!.use {
            assert(it.count == 1)
            assert(it.moveToFirst())
            assertEquals(0L, it.getLong(0))
        }
    }
}
