/*
 * 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/>
 */
package tech.libeufin.bank

import tech.libeufin.common.*

/* ----- Currency checks ----- */

fun BankConfig.checkRegionalCurrency(amount: TalerAmount) {
    if (amount.currency != regionalCurrency) throw badRequest(
        "Wrong currency: expected regional currency $regionalCurrency got ${amount.currency}",
        TalerErrorCode.GENERIC_CURRENCY_MISMATCH
    )
}

fun BankConfig.checkFiatCurrency(amount: TalerAmount) {
    if (amount.currency != fiatCurrency) throw badRequest(
        "Wrong currency: expected fiat currency $fiatCurrency got ${amount.currency}",
        TalerErrorCode.GENERIC_CURRENCY_MISMATCH
    )
}

fun BankConfig.checkCurrency(input: ConversionRateClassInput) {
    for (regionalAmount in sequenceOf(input.cashin_fee, input.cashout_min_amount).filterNotNull()) {
        this.checkRegionalCurrency(regionalAmount)
    }
    for (fiatAmount in sequenceOf(input.cashout_fee, input.cashin_min_amount).filterNotNull()) {
        this.checkFiatCurrency(fiatAmount)
    }
}

/* ----- Common errors ----- */

fun unknownAccount(id: String) = notFound(
    "Account '$id' not found",
    TalerErrorCode.BANK_UNKNOWN_ACCOUNT
)

fun unknownCreditorAccount(id: String) = conflict(
    "Creditor account '$id' not found",
    TalerErrorCode.BANK_UNKNOWN_CREDITOR
)

fun unsupportedTanChannel(channel: TanChannel) = conflict(
    "Unsupported tan channel $channel",
    TalerErrorCode.BANK_TAN_CHANNEL_NOT_SUPPORTED
)

fun notExchange(username: String): ApiException = conflict(
    "Account '$username' is not an exchange account.",
    TalerErrorCode.BANK_ACCOUNT_IS_NOT_EXCHANGE
)

fun unknownConversionClass(id: Long?): ApiException = conflict(
    "Unknown conversion rate class $id",
    TalerErrorCode.BANK_CONVERSION_RATE_CLASS_UNKNOWN
)