/*
 * This file is part of LibEuFin.
 * Copyright (C) 2026 Taler Systems S.A.

 * LibEuFin is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation; either version 3, or
 * (at your option) any later version.

 * LibEuFin is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General
 * Public License for more details.

 * You should have received a copy of the GNU Affero General Public
 * License along with LibEuFin; see the file COPYING.  If not, see
 * <http://www.gnu.org/licenses/>
 */

import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.server.testing.*
import org.junit.Test
import sun.misc.Unsafe
import tech.libeufin.bank.bankConfig
import tech.libeufin.bank.corebankWebApp
import tech.libeufin.bank.db.Database
import tech.libeufin.common.*
import java.io.File
import kotlin.io.path.Path
import kotlin.test.*

class OpenApiTest {
    private fun fakeDatabase(): Database {
        val field = Unsafe::class.java.getDeclaredField("theUnsafe")
        field.isAccessible = true
        val unsafe = field.get(null) as Unsafe
        return unsafe.allocateInstance(Database::class.java) as Database
    }

    @Test
    fun generateSpec() {
        val cfg = bankConfig(Path("conf/test.conf"))
        testApplication {
            application {
                corebankWebApp(fakeDatabase(), cfg, serveSpec = true)
            }
            val resp = client.get("/openapi.yaml")
            resp.assertOk()
            val spec = resp.bodyAsText()
            assertTrue(spec.contains("openapi: 3.1.0"), "Response should be a valid OpenAPI spec")
            assertTrue(spec.contains("LibEuFin Bank API"), "Spec should contain the API title")
            val outFile = File("build/openapi.yaml")
            outFile.writeText(spec)
            println("OpenAPI spec written to ${outFile.absolutePath}")
        }
    }
}
