/*
 * 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/>
 */

package tech.libeufin.bank.db

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

/** Data access logic for transfer specific logic */
class TransferDAO(private val db: Database) {
    /** Result of prepared transfer registration */
    sealed interface RegistrationResult {
        data class Success(val uuid: UUID?): RegistrationResult
        data object UnknownAccount: RegistrationResult
        data object NotExchange: RegistrationResult
        data object ReservePubReuse: RegistrationResult
    }

    /** Register a prepared transfer */
    suspend fun register(
        exchangeUsername: String,
        type: TransferType,
        accountPub: EddsaPublicKey,
        authPub: EddsaPublicKey,
        authSig: EddsaSignature,
        recurrent: Boolean,
        amount: TalerAmount,
        timestamp: Instant
    ): RegistrationResult = db.serializable(
        """
        SELECT out_unknown_account, out_not_exchange, out_reserve_pub_reuse, out_withdrawal_uuid
        FROM register_prepared_transfers (
            ?, ?::taler_incoming_type, ?, ?, ?, ?, (?, ?)::taler_amount, ?, ?
        )
        """
    ) {
        bind(exchangeUsername)
        bind(type)
        bind(accountPub)
        bind(authPub)
        bind(authSig)
        bind(recurrent)
        bind(amount)
        bind(timestamp)
        bind("Taler prepared MAP:$authPub")
        one {
            when {
                it.getBoolean("out_unknown_account") -> RegistrationResult.UnknownAccount
                it.getBoolean("out_not_exchange") -> RegistrationResult.NotExchange
                it.getBoolean("out_reserve_pub_reuse") -> RegistrationResult.ReservePubReuse
                else -> RegistrationResult.Success(it.getOptObject("out_withdrawal_uuid"))
            }
        }
    }

    /** Unregister a prepared transfer */
    suspend fun unregister(
        authorizationPub: EddsaPublicKey,
        timestamp: Instant
    ) = db.serializable(
        "SELECT out_found FROM delete_prepared_transfers(?,?)",
        {
            bind(authorizationPub)
            bind(timestamp)
            one {
                it.getBoolean(1)
            }
        }
    )
}