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

package tech.libeufin.bank.db

import tech.libeufin.common.*
import tech.libeufin.common.db.*
import java.time.Instant

/** Data access logic for exchange specific logic */
class ExchangeDAO(private val db: Database) {
    /** Query [exchangeId] history of taler incoming transactions  */
    suspend fun incomingHistory(
        params: HistoryParams, 
        exchangeId: Long
    ): List<IncomingBankTransaction> 
        = db.poolHistory(params, exchangeId, db::listenIncoming,  """
            SELECT
                bank_transaction_id
                ,transaction_date
                ,(amount).val AS amount_val
                ,(amount).frac AS amount_frac
                ,debtor_payto
                ,debtor_name
                ,type
                ,metadata
                ,authorization_pub
                ,authorization_sig
            FROM taler_exchange_incoming AS tfr
                JOIN bank_account_transactions AS txs
                    ON bank_transaction=txs.bank_transaction_id
            WHERE
        """) {
            val type = it.getEnum<IncomingType>("type")
            when (type) {
                IncomingType.reserve -> IncomingReserveTransaction(
                    row_id = it.getLong("bank_transaction_id"),
                    date = it.getTalerTimestamp("transaction_date"),
                    amount = it.getAmount("amount", db.bankCurrency),
                    debit_account = it.getBankPayto("debtor_payto", "debtor_name", db.ctx),
                    reserve_pub = EddsaPublicKey(it.getBytes("metadata")),
                    authorization_pub = it.getOptKey("authorization_pub"),
                    authorization_sig = it.getOptSig("authorization_sig")
                )
                IncomingType.kyc -> IncomingKycAuthTransaction(
                    row_id = it.getLong("bank_transaction_id"),
                    date = it.getTalerTimestamp("transaction_date"),
                    amount = it.getAmount("amount", db.bankCurrency),
                    debit_account = it.getBankPayto("debtor_payto", "debtor_name", db.ctx),
                    account_pub = EddsaPublicKey(it.getBytes("metadata")),
                    authorization_pub = it.getOptKey("authorization_pub"),
                    authorization_sig = it.getOptSig("authorization_sig")
                )
                IncomingType.map -> throw UnsupportedOperationException()
            }
        }
    
    /** Query [exchangeId] history of taler outgoing transactions  */
    suspend fun outgoingHistory(
        params: HistoryParams, 
        exchangeId: Long
    ): List<OutgoingTransaction> 
        = db.poolHistory(params, exchangeId, db::listenOutgoing,  """
            SELECT
                bank_transaction_id
                ,transaction_date
                ,(txs.amount).val AS amount_val
                ,(txs.amount).frac AS amount_frac
                ,txs.creditor_payto
                ,txs.creditor_name
                ,wtid
                ,exchange_base_url
                ,transfer_operations.metadata
            FROM taler_exchange_outgoing AS tfr
                JOIN transfer_operations USING (exchange_outgoing_id)
                JOIN bank_account_transactions AS txs
                    ON bank_transaction=txs.bank_transaction_id
            WHERE
        """) {
            OutgoingTransaction(
                row_id = it.getLong("bank_transaction_id"),
                date = it.getTalerTimestamp("transaction_date"),
                amount = it.getAmount("amount", db.bankCurrency),
                credit_account = it.getBankPayto("creditor_payto", "creditor_name", db.ctx),
                wtid = ShortHashCode(it.getBytes("wtid")),
                exchange_base_url = it.getString("exchange_base_url"),
                metadata = it.getString("metadata"),
                debit_fee = null
            )
        }

    /** Result of taler transfer transaction creation */
    sealed interface TransferResult {
        /** Transaction [id] and wire transfer [timestamp] */
        data class Success(val id: Long, val timestamp: TalerTimestamp): TransferResult
        data object NotAnExchange: TransferResult
        data object UnknownExchange: TransferResult
        data object BothPartyAreExchange: TransferResult
        data object BalanceInsufficient: TransferResult
        data object ReserveUidReuse: TransferResult
        data object WtidReuse: TransferResult
        data object AdminCreditor: TransferResult
    }

    /** Perform a Taler transfer */
    suspend fun transfer(
        req: TransferRequest,
        username: String,
        timestamp: Instant,
        conversion: Boolean
    ): TransferResult = db.serializable(
        """
        SELECT
            out_debtor_not_found
            ,out_debtor_not_exchange
            ,out_both_exchanges
            ,out_request_uid_reuse
            ,out_wtid_reuse
            ,out_exchange_balance_insufficient
            ,out_creditor_admin
            ,out_tx_row_id
            ,out_timestamp
        FROM
            taler_transfer (
                ?, ?, ?,
                (?,?)::taler_amount,
                ?, ?, ?, ?, ?, ?
            );
        """
    ) {
        val subject = fmtOutgoingSubject(req.wtid, req.exchange_base_url, req.metadata)

        bind(req.request_uid)
        bind(req.wtid)
        bind(subject)
        bind(req.amount)
        bind(req.exchange_base_url.url.toString())
        bind(req.metadata)
        bind(req.credit_account.canonical)
        bind(username)
        bind(timestamp)
        bind(conversion)
        one {
            when {
                it.getBoolean("out_debtor_not_found") -> TransferResult.UnknownExchange
                it.getBoolean("out_debtor_not_exchange") -> TransferResult.NotAnExchange
                it.getBoolean("out_both_exchanges") -> TransferResult.BothPartyAreExchange
                it.getBoolean("out_exchange_balance_insufficient") -> TransferResult.BalanceInsufficient
                it.getBoolean("out_request_uid_reuse") -> TransferResult.ReserveUidReuse
                it.getBoolean("out_wtid_reuse") -> TransferResult.WtidReuse
                it.getBoolean("out_creditor_admin") -> TransferResult.AdminCreditor
                else -> TransferResult.Success(
                    id = it.getLong("out_tx_row_id"),
                    timestamp = it.getTalerTimestamp("out_timestamp")
                )
            }
        }
    }

    /** Get status of transfer [txId] of account [exchangeId] */
    suspend fun getTransfer(
        exchangeId: Long,
        txId: Long
    ): TransferStatus? = db.serializable(
        """
        SELECT
            wtid
            ,exchange_base_url
            ,metadata
            ,transfer_date
            ,(amount).val AS amount_val
            ,(amount).frac AS amount_frac
            ,creditor_payto
            ,status
            ,status_msg
        FROM transfer_operations 
        WHERE transfer_operation_id=? AND exchange_id=?
        """
    ) {
        bind(txId)
        bind(exchangeId)
        oneOrNull {
            TransferStatus(
                status = it.getEnum<TransferStatusState>("status"),
                status_msg = it.getString("status_msg"),
                amount = it.getAmount("amount", db.bankCurrency),
                origin_exchange_url = it.getString("exchange_base_url"),
                metadata = it.getString("metadata"),
                wtid = ShortHashCode(it.getBytes("wtid")),
                credit_account = it.getBankPayto("creditor_payto", null, db.ctx),
                timestamp = it.getTalerTimestamp("transfer_date"),
            )
        }
    }

    /** Get a page of transfers status of account [exchangeId] */
    suspend fun pageTransfer(
        params: PageParams,
        exchangeId: Long,
        status: TransferStatusState?
    ): List<TransferListStatus> = db.page(
        params,
        "transfer_operation_id",
        """
        SELECT
            transfer_operation_id
            ,transfer_date
            ,(amount).val AS amount_val
            ,(amount).frac AS amount_frac
            ,creditor_payto
            ,status
        FROM transfer_operations
        WHERE exchange_id=? AND ${
            when (status) {
                null -> ""
                else -> "status=?::transfer_status AND"
            }               
        }
        """,
        {
            bind(exchangeId)
            if (status != null) {
                bind(status)
            }
        }
    ) {
        TransferListStatus(
            row_id = it.getLong("transfer_operation_id"),
            status = it.getEnum<TransferStatusState>("status"),
            amount = it.getAmount("amount", db.bankCurrency),
            credit_account = it.getBankPayto("creditor_payto", null, db.ctx),
            timestamp = it.getTalerTimestamp("transfer_date"),
        )
    }

    /** Result of taler add incoming transaction creation */
    sealed interface AddIncomingResult {
        /** Transaction [id] and wire transfer [timestamp] */
        data class Success(val id: Long, val timestamp: TalerTimestamp, val pending: Boolean): AddIncomingResult
        data object NotAnExchange: AddIncomingResult
        data object UnknownExchange: AddIncomingResult
        data object UnknownDebtor: AddIncomingResult
        data object BothPartyAreExchange: AddIncomingResult
        data object ReservePubReuse: AddIncomingResult
        data object UnknownMapping: AddIncomingResult
        data object MappingReuse: AddIncomingResult
        data object BalanceInsufficient: AddIncomingResult
    }

     /** Add a new taler incoming transaction */
    suspend fun addIncoming(
        amount: TalerAmount,
        debitAccount: Payto,
        subject: String,
        username: String,
        timestamp: Instant,
        metadata: IncomingSubject
    ): AddIncomingResult = db.serializable(
        """
        SELECT
            out_creditor_not_found
            ,out_creditor_not_exchange
            ,out_debtor_not_found
            ,out_both_exchanges
            ,out_reserve_pub_reuse
            ,out_mapping_reuse
            ,out_unknown_mapping
            ,out_debitor_balance_insufficient
            ,out_tx_row_id
            ,out_pending
        FROM
            taler_add_incoming (
                ?, ?, (?,?)::taler_amount,
                ?, ?, ?, ?::taler_incoming_type
            );
        """
    ) {
        bind(metadata.key)
        bind(subject)
        bind(amount)
        bind(debitAccount.canonical)
        bind(username)
        bind(timestamp)
        bind(metadata.type)

        one {
            when {
                it.getBoolean("out_creditor_not_found") -> AddIncomingResult.UnknownExchange 
                it.getBoolean("out_creditor_not_exchange") -> AddIncomingResult.NotAnExchange
                it.getBoolean("out_debtor_not_found") -> AddIncomingResult.UnknownDebtor
                it.getBoolean("out_both_exchanges") -> AddIncomingResult.BothPartyAreExchange
                it.getBoolean("out_debitor_balance_insufficient") -> AddIncomingResult.BalanceInsufficient
                it.getBoolean("out_reserve_pub_reuse") -> AddIncomingResult.ReservePubReuse
                it.getBoolean("out_mapping_reuse") -> AddIncomingResult.MappingReuse
                it.getBoolean("out_unknown_mapping") -> AddIncomingResult.UnknownMapping
                else -> AddIncomingResult.Success(
                    id = it.getLong("out_tx_row_id"),
                    timestamp = TalerTimestamp(timestamp),
                    pending = it.getBoolean("out_pending")
                )
            }
        }
    }
}