package ch.threema.storage

import java.io.File
import java.time.Instant
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.fail

class DatabaseSchemaCreatorTest {

    private val schemaFile = File("src/test/resources/database/schema.sql")

    @Test
    fun `creation statements`() {
        if (schemaFile.exists() && schemaFile.length() > 0) {
            assertEquals(
                schemaFile.readText().substringAfter("\n\n"),
                getSchemaDump(),
            )
        } else {
            schemaFile.writeText(
                """
                    -- This file was generated by DatabaseSchemaCreatorTest on ${Instant.now()}. --
                    -- If you intentionally made changes to the schema, delete or clear this file and rerun the test to generate a new one, then verify and commit the changes. --
                    
                    
                """.trimIndent() + getSchemaDump(),
            )
            fail("Schema file was created. Failing test now to ensure that you don't forget to commit the file.")
        }
    }

    private fun getSchemaDump(): String =
        DatabaseSchemaCreator.getCreationStatements().joinToString(separator = "\n") { statement ->
            if (statement.endsWith(";")) {
                statement
            } else {
                "$statement;"
            }
        }
}
