/*
 * This file is part of LibEuFin.
 * Copyright (C) 2024-2025 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/>
 */

package tech.libeufin.ebics

import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.plugins.*
import io.ktor.client.engine.mock.*
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter

/** Use for unit testing */
var MOCK_ENGINE: MockEngine? = null

/** Create an HTTP client for EBICS requests */
fun httpClient(): HttpClient = MOCK_ENGINE?.let { 
    HttpClient(it)
} ?: HttpClient {
    install(HttpTimeout) {
        // It can take a lot of time for the bank to generate documents
        socketTimeoutMillis = 5 * 60 * 1000
    }
}

/** Gets an HTTP client whose requests are going to be served by 'handler' */
fun getMockedClient(
    handler: MockRequestHandleScope.(HttpRequestData) -> HttpResponseData
): HttpClient = HttpClient(MockEngine) {
    followRedirects = false
    engine {
        addHandler {
            request -> handler(request)
        }
    }
}

private lateinit var steps: Iterator<(String) -> ByteArray>

object BadRequest: Exception()

fun setMock(sequences: Sequence<(String) -> ByteArray>) {
    steps = sequences.iterator()
    if (MOCK_ENGINE == null) {
        val cfg: MockEngineConfig = MockEngineConfig()
        cfg.addHandler { req ->
            val body = String((req.body as OutgoingContent.ByteArrayContent).bytes())
            val handler = steps.next()
            try {
                val res = handler(body)
                respond(res)
            } catch (e: BadRequest) {
                respondBadRequest()
            }
        }
        MOCK_ENGINE = MockEngine(cfg)
    }
}