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

import io.ktor.http.*
import org.junit.Test
import tech.libeufin.common.*
import tech.libeufin.common.db.*
import tech.libeufin.common.test.*
import kotlin.test.*

class AmountTest {
    // Test amount computation in db
    @Test
    fun computationTest() = bankSetup { db -> db.conn { conn ->
        conn.execSQLUpdate("UPDATE libeufin_bank.bank_accounts SET balance.val = 100000 WHERE internal_payto = '${customerPayto.canonical}'")
        val stmt = conn.talerStatement("""
            UPDATE libeufin_bank.bank_accounts 
                SET balance = (?, ?)::taler_amount
                    ,has_debt = ?
                    ,max_debt = (?, ?)::taler_amount
            WHERE internal_payto = '${merchantPayto.canonical}'
        """)
        suspend fun routine(
            balance: TalerAmount,
            hasDebt: Boolean,
            maxDebt: TalerAmount,
            amount: TalerAmount
        ): Boolean {
            stmt.bind(balance)
            stmt.bind(hasDebt)
            stmt.bind(maxDebt)

            // Check bank transaction
            stmt.executeUpdate()
            val txRes = client.postA("/accounts/merchant/transactions") {
                json {
                    "payto_uri" to "$customerPayto?message="
                    "amount" to amount
                }
            }
            val txBool = when {
                txRes.isStatus(HttpStatusCode.OK, null) -> true
                txRes.isStatus(HttpStatusCode.Conflict, TalerErrorCode.BANK_UNALLOWED_DEBIT) -> false
                else -> throw Exception("Unexpected error $txRes")
            }

            // Check whithdraw 
            stmt.bind(balance)
            stmt.bind(hasDebt)
            stmt.bind(maxDebt)
            stmt.executeUpdate()
            for ((amount, suggested) in listOf(Pair(amount, null), Pair(null, amount), Pair(amount, amount))) {
                val wRes = client.postA("/accounts/merchant/withdrawals") {
                    json { 
                        "amount" to amount
                        "suggested_amount" to suggested
                    } 
                }
                val wBool = when {
                    wRes.isStatus(HttpStatusCode.OK, null) -> true
                    wRes.isStatus(HttpStatusCode.Conflict, TalerErrorCode.BANK_UNALLOWED_DEBIT) -> false
                    else -> throw Exception("Unexpected error $wRes")
                }
                // Logic must be the same
                assertEquals(wBool, txBool)
            }
            
            return txBool
        }

        // Balance enough, assert for true
        assert(routine(
            balance = TalerAmount(10, 0, "KUDOS"),
            hasDebt = false,
            maxDebt = TalerAmount(100, 0, "KUDOS"),
            amount = TalerAmount(8, 0, "KUDOS"),
        ))
        // Balance still sufficient, thanks for big enough debt permission.  Assert true.
        assert(routine(
            balance = TalerAmount(10, 0, "KUDOS"),
            hasDebt = false,
            maxDebt = TalerAmount(100, 0, "KUDOS"),
            amount = TalerAmount(80, 0, "KUDOS"),
        ))
        // Balance not enough, max debt cannot cover, asserting for false.
        assert(!routine(
            balance = TalerAmount(10, 0, "KUDOS"),
            hasDebt = true,
            maxDebt = TalerAmount(50, 0, "KUDOS"),
            amount = TalerAmount(80, 0, "KUDOS"),
        ))
        // Balance becomes enough, due to a larger max debt, asserting for true.
        assert(routine(
            balance = TalerAmount(10, 0, "KUDOS"),
            hasDebt = false,
            maxDebt = TalerAmount(70, 0, "KUDOS"),
            amount = TalerAmount(80, 0, "KUDOS"),
        ))
        // Max debt not enough for the smallest fraction, asserting for false
        assert(!routine(
            balance = TalerAmount(0, 0, "KUDOS"),
            hasDebt = false,
            maxDebt = TalerAmount(0, 1, "KUDOS"),
            amount = TalerAmount(0, 2, "KUDOS"),
        ))
        // Same as above, but already in debt.
        assert(!routine(
            balance = TalerAmount(0, 1, "KUDOS"),
            hasDebt = true,
            maxDebt = TalerAmount(0, 1, "KUDOS"),
            amount = TalerAmount(0, 1, "KUDOS"),
        ))
    }}

    // Max withdrawal amount computation in db
    @Test
    fun maxComputationTest() = bankSetup { db -> db.conn { conn ->
        val update = conn.talerStatement("""
            UPDATE libeufin_bank.bank_accounts 
                SET balance = (?, ?)::taler_amount
                    ,has_debt = ?
                    ,max_debt = (?, ?)::taler_amount
            WHERE bank_account_id = 1
        """)
        val select = conn.talerStatement("""
            SELECT
                (max_amount).val as max_amount_val
                ,(max_amount).frac as max_amount_frac
            FROM account_max_amount(1, (?, ?)::taler_amount) AS max_amount
        """)
        suspend fun routine(
            balance: TalerAmount,
            hasDebt: Boolean,
            maxDebt: TalerAmount
        ): TalerAmount {
            update.apply {
                bind(balance)
                bind(hasDebt)
                bind(maxDebt)
                executeUpdate()
            }
            select.bind(TalerAmount.max("KUDOS"))
            return select.one { it.getAmount("max_amount", "KUDOS") }
        }

        // Without debt
        assertEquals(TalerAmount(110, 3, "KUDOS"), routine(
            balance = TalerAmount(10, 1, "KUDOS"),
            hasDebt = false,
            maxDebt = TalerAmount(100, 2, "KUDOS"),
        ))
        // With debt
        assertEquals(TalerAmount(90, 1, "KUDOS"), routine(
            balance = TalerAmount(10, 1, "KUDOS"),
            hasDebt = true,
            maxDebt = TalerAmount(100, 2, "KUDOS"),
        ))
    }}

    @Test
    fun parseRoundTrip() {
        for (amount in listOf("EUR:4", "EUR:0.02", "EUR:4.12")) {
            assertEquals(amount, TalerAmount(amount).toString())
        }
    }
    
    @Test
    fun normalize() = dbSetup { db ->
        db.conn { conn ->
            val stmt = conn.talerStatement("SELECT normalized.val, normalized.frac FROM amount_normalize((?, ?)::taler_amount) as normalized")
            fun TalerAmount.db(): TalerAmount {
                stmt.bind(value)
                stmt.bind(frac)
                return stmt.one {
                    TalerAmount(
                        it.getLong(1),
                        it.getInt(2),
                        "EUR"
                    )
                }
            }

            fun assertNormalize(from: TalerAmount, to: TalerAmount) {
                val normalized = from.normalize()
                assertEquals(to, normalized, "Bad normalization")
                val dbNormalized = from.db()
                assertEquals(normalized, dbNormalized, "DB vs code behavior")
            }

            fun assertErr(from: TalerAmount, msg: String) {
                assertFails { from.normalize() }
                assertException(msg) { from.db() }
            }
    
            assertNormalize(TalerAmount(4L, 2 * TalerAmount.FRACTION_BASE, "EUR"), TalerAmount("EUR:6"))
            assertNormalize(TalerAmount(4L, 2 * TalerAmount.FRACTION_BASE + 1, "EUR"), TalerAmount("EUR:6.00000001"))
            assertNormalize(TalerAmount("EUR:${TalerAmount.MAX_VALUE}.99999999"), TalerAmount("EUR:${TalerAmount.MAX_VALUE}.99999999"))
            assertErr(TalerAmount(Long.MAX_VALUE, TalerAmount.FRACTION_BASE, "EUR"), "ERROR: bigint out of range")
            assertErr(TalerAmount(TalerAmount.MAX_VALUE, TalerAmount.FRACTION_BASE , "EUR"), "ERROR: amount value overflowed")

            for (amount in listOf(TalerAmount.max("EUR"), TalerAmount.zero("EUR"))) {
                assertNormalize(amount, amount)
            }
        }
    }

    @Test
    fun add() = dbSetup { db ->
        db.conn { conn ->
            val stmt = conn.talerStatement("SELECT sum.val, sum.frac FROM amount_add((?, ?)::taler_amount, (?, ?)::taler_amount) as sum")
            fun TalerAmount.db(increment: TalerAmount): TalerAmount {
                stmt.bind(value)
                stmt.bind(frac)
                stmt.bind(increment)
                return stmt.one {
                    TalerAmount(
                        it.getLong(1),
                        it.getInt(2),
                        "EUR"
                    )
                }
            }

            fun assertAdd(a: TalerAmount, b: TalerAmount, sum: TalerAmount) {
                val codeSum = a + b
                assertEquals(sum, codeSum, "Bad sum")
                val dbSum = a.db(b)
                assertEquals(codeSum, dbSum, "DB vs code behavior")
            }

            fun assertErr(a: TalerAmount, b: TalerAmount, msg: String) {
                assertFails { a + b }
                assertException(msg) { a.db(b) }
            }
            
            assertAdd(TalerAmount.max("EUR"), TalerAmount.zero("EUR"), TalerAmount.max("EUR"))
            assertAdd(TalerAmount.zero("EUR"), TalerAmount.zero("EUR"), TalerAmount.zero("EUR"))
            assertAdd(TalerAmount("EUR:6.41"), TalerAmount("EUR:4.69"), TalerAmount("EUR:11.1"))
            assertAdd(TalerAmount("EUR:${TalerAmount.MAX_VALUE}"), TalerAmount("EUR:0.99999999"), TalerAmount("EUR:${TalerAmount.MAX_VALUE}.99999999"))
            assertErr(TalerAmount(TalerAmount.MAX_VALUE - 5, 0, "EUR"), TalerAmount(6, 0, "EUR"), "ERROR: amount value overflowed")
            assertErr(TalerAmount(Long.MAX_VALUE, 0, "EUR"), TalerAmount(1, 0, "EUR"), "ERROR: bigint out of range")
            assertErr(TalerAmount(TalerAmount.MAX_VALUE - 5, TalerAmount.FRACTION_BASE - 1, "EUR"), TalerAmount(5, 2, "EUR"), "ERROR: amount value overflowed")
            assertErr(TalerAmount(0, Int.MAX_VALUE, "EUR"), TalerAmount(0, 1, "EUR"), "ERROR: integer out of range")
        }
    }

    @Test
    fun conversionApply() = dbSetup { db ->
        db.conn { conn ->
            fun apply(nb: TalerAmount, times: DecimalNumber, tiny: DecimalNumber = DecimalNumber("0.00000001"), roundingMode: String = "zero"): TalerAmount {
                val stmt = conn.talerStatement("SELECT (result).val, (result).frac FROM conversion_apply_ratio((?, ?)::taler_amount, (?, ?)::taler_amount, (0, 0)::taler_amount, (?, ?)::taler_amount, ?::rounding_mode)")
                stmt.bind(nb)
                stmt.bind(times)
                stmt.bind(tiny)
                stmt.bind(roundingMode)
                return stmt.one {
                    TalerAmount(
                        it.getLong(1),
                        it.getInt(2),
                        nb.currency
                    )
                }
            }
    
            assertEquals(TalerAmount("EUR:30.0629"), apply(TalerAmount("EUR:6.41"), DecimalNumber("4.69")))
            assertEquals(TalerAmount("EUR:6.41000641"), apply(TalerAmount("EUR:6.41"), DecimalNumber("1.000001")))
            assertEquals(TalerAmount("EUR:2.49999997"), apply(TalerAmount("EUR:0.99999999"), DecimalNumber("2.5")))
            assertEquals(TalerAmount("EUR:${TalerAmount.MAX_VALUE}.99999999"), apply(TalerAmount("EUR:${TalerAmount.MAX_VALUE}.99999999"), DecimalNumber("1")))
            assertEquals(TalerAmount("EUR:${TalerAmount.MAX_VALUE}"), apply(TalerAmount("EUR:${TalerAmount.MAX_VALUE/4}"), DecimalNumber("4")))
            assertException("ERROR: amount value overflowed") { apply(TalerAmount(TalerAmount.MAX_VALUE/3, 0, "EUR"), DecimalNumber("3.00000001")) }
            assertException("ERROR: amount value overflowed") { apply(TalerAmount((TalerAmount.MAX_VALUE+2)/2, 0, "EUR"), DecimalNumber("2")) }
            assertException("ERROR: numeric field overflow") { apply(TalerAmount(Long.MAX_VALUE, 0, "EUR"), DecimalNumber("1")) }

            // Check rounding mode
            for ((mode, rounding) in listOf(
                Pair("zero", listOf(Pair(1, listOf(10, 11, 12, 12, 14, 15, 16, 17, 18, 19)))),
                Pair("up", listOf(Pair(1, listOf(10)), Pair(2, listOf(11, 12, 12, 14, 15, 16, 17, 18, 19)))),
                Pair("nearest", listOf(Pair(1, listOf(10, 11, 12, 12, 14)), Pair(2, listOf(15, 16, 17, 18, 19))))
            )) {
                for ((rounded, amounts) in rounding) {
                    for (amount in amounts) {
                        // Check euro
                        assertEquals(TalerAmount("EUR:0.0$rounded"), apply(TalerAmount("EUR:$amount"), DecimalNumber("0.001"), DecimalNumber("0.01"), mode))
                        // Check kudos
                        assertEquals(TalerAmount("KUDOS:0.0000000$rounded"), apply(TalerAmount("KUDOS:0.$amount"), DecimalNumber("0.0000001"), roundingMode = mode))
                    }
                }
            }
            
            // Check hungarian rounding
            for ((mode, rounding) in listOf(
                Pair("zero", listOf(Pair(10, listOf(10, 11, 12, 13, 14)), Pair(15, listOf(15, 16, 17, 18, 19)))),
                Pair("up", listOf(Pair(10, listOf(10)), Pair(15, listOf(11, 12, 13, 14, 15)), Pair(20, listOf(16, 17, 18, 19)))),
                Pair("nearest", listOf(Pair(10, listOf(10, 11, 12)), Pair(15, listOf(13, 14, 15, 16, 17)), Pair(20, listOf(18, 19))))
            )) {
                for ((rounded, amounts) in rounding) {
                    for (amount in amounts) {
                        assertEquals(TalerAmount("HUF:$rounded"), apply(TalerAmount("HUF:$amount"), DecimalNumber("1"), DecimalNumber("5"), mode))
                    }
                }
            }
            for (mode in listOf("zero", "up", "nearest")) {
                assertEquals(TalerAmount("HUF:5"), apply(TalerAmount("HUF:5"), DecimalNumber("1"), DecimalNumber("1"), mode))
            }
        }
    }

    @Test
    fun conversionRevert() = dbSetup { db ->
        db.conn { conn ->
            val applyStmt = conn.talerStatement("SELECT (result).val, (result).frac FROM conversion_apply_ratio((?, ?)::taler_amount, (?, ?)::taler_amount, (0, 0)::taler_amount, (?, ?)::taler_amount, ?::rounding_mode)")
            fun TalerAmount.apply(ratio: DecimalNumber, tiny: DecimalNumber = DecimalNumber("0.00000001"), roundingMode: String = "zero"): TalerAmount {
                applyStmt.bind(this)
                applyStmt.bind(ratio)
                applyStmt.bind(tiny)
                applyStmt.bind(roundingMode)
                return applyStmt.one {
                    TalerAmount(
                        it.getLong(1),
                        it.getInt(2),
                        currency
                    )
                }
            }

            val revertStmt = conn.talerStatement("SELECT (result).val, (result).frac FROM conversion_revert_ratio((?, ?)::taler_amount, (?, ?)::taler_amount, (0, 0)::taler_amount, (?, ?)::taler_amount, ?::rounding_mode, (?, ?)::taler_amount)")
            fun TalerAmount.revert(ratio: DecimalNumber, tiny: DecimalNumber = DecimalNumber("0.00000001"), roundingMode: String = "zero", reverseTiny: DecimalNumber = DecimalNumber("0.00000001")): TalerAmount {
                revertStmt.bind(this)
                revertStmt.bind(ratio)
                revertStmt.bind(tiny)
                revertStmt.bind(roundingMode)
                revertStmt.bind(reverseTiny)
                return revertStmt.one {
                    TalerAmount(
                        it.getLong(1),
                        it.getInt(2),
                        currency
                    )
                }
            }
    
            assertEquals(TalerAmount("EUR:6.41"), TalerAmount("EUR:30.0629").revert(DecimalNumber("4.69")))
            assertEquals(TalerAmount("EUR:6.41"), TalerAmount("EUR:6.41000641").revert(DecimalNumber("1.000001")))
            assertEquals(TalerAmount("EUR:1"), TalerAmount("EUR:2.49999998").revert(DecimalNumber("2.5")))
            assertEquals(TalerAmount("EUR:${TalerAmount.MAX_VALUE}.99999999"), TalerAmount("EUR:${TalerAmount.MAX_VALUE}.99999999").revert(DecimalNumber("1")))
            assertEquals(TalerAmount("EUR:${TalerAmount.MAX_VALUE}"), TalerAmount("EUR:${TalerAmount.MAX_VALUE/4}").revert(DecimalNumber("0.25")))
            assertException("ERROR: amount value overflowed") { TalerAmount(TalerAmount.MAX_VALUE/4, 0, "EUR").revert(DecimalNumber("0.24999999")) }
            assertException("ERROR: amount value overflowed") { TalerAmount((TalerAmount.MAX_VALUE+2)/2, 0, "EUR").revert(DecimalNumber("0.5")) }
            assertException("ERROR: numeric field overflow") { TalerAmount(Long.MAX_VALUE, 0, "EUR").revert(DecimalNumber("1")) }


            for (mode in sequenceOf("zero", "up", "nearest")) {
                for (tiny in sequenceOf("0.01", "0.00000001", "1", "2", "3", "5").map(::DecimalNumber)) {
                    for (amount in sequenceOf(10, 11, 12, 12, 14, 15, 16, 17, 18, 19).map { TalerAmount("EUR:$it") }) {
                        for (ratio in sequenceOf("1", "1.25", "1.26", "0.01", "0.001", "0.00000001").map(::DecimalNumber)) {
                            for (reverseTiny in sequenceOf("0.01", "0.00000001", "1").map(::DecimalNumber)) {
                                // Apply ratio
                                val rounded = amount.apply(ratio, tiny, mode)
                                // Revert ratio  
                                val revert = rounded.revert(ratio, tiny, mode, reverseTiny)
                                // Check applying ratio again give the same result
                                val check = revert.apply(ratio, tiny, mode)
                                println("$amount $rounded $revert $check $ratio $tiny $mode")
                                assertEquals(rounded, check)
                            }
                        }
                    }
                }
            }
        }
    }

    @Test
    fun apiError() = bankSetup { 
        val base = obj {
            "payto_uri" to "$exchangePayto?message=payout"
        }

        // Check OK
        client.postA("/accounts/merchant/transactions") {
            json(base) { "amount" to "KUDOS:0.3ABC" }
        }.assertBadRequest(TalerErrorCode.BANK_BAD_FORMAT_AMOUNT)
        client.postA("/accounts/merchant/transactions") {
            json(base) { "amount" to "KUDOS:999999999999999999" }
        }.assertBadRequest(TalerErrorCode.BANK_NUMBER_TOO_BIG)
    }
}