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

/* This file contains the Taler Integration API endpoints,
* that are typically requested by wallets.  */
package tech.libeufin.bank.api

import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.github.smiley4.ktoropenapi.*
import tech.libeufin.bank.*
import tech.libeufin.bank.db.AbortResult
import tech.libeufin.bank.db.Database
import tech.libeufin.bank.db.WithdrawalDAO.WithdrawalSelectionResult
import tech.libeufin.common.*

fun Routing.bankIntegrationApi(db: Database, ctx: BankConfig) {
    get("/taler-integration/config", {
        operationId = "getIntegrationConfig"
        description = "Get bank integration configuration"
        tags = listOf("Bank Integration")
        response {
            code(HttpStatusCode.OK) { description = "Integration configuration"; body<TalerIntegrationConfigResponse>() }
        }
    }) {
        call.respond(TalerIntegrationConfigResponse(
            currency = ctx.regionalCurrency,
            currency_specification = ctx.regionalCurrencySpec
        ))
    }

    // Note: wopid acts as an authentication token.
    get("/taler-integration/withdrawal-operation/{wopid}", {
        operationId = "getIntegrationWithdrawalStatus"
        description = "Get withdrawal operation status"
        tags = listOf("Bank Integration")
        request {
            pathParameter<String>("wopid") { description = "Withdrawal operation ID" }
            queryParameter<Long>("timeout_ms") {
                description = "Timeout for long polling in milliseconds (default: 0, no long polling)"
                required = false
            }
            queryParameter<String>("old_state") {
                description = "Previous state for long polling (pending, aborted, selected, confirmed). Default: pending"
                required = false
            }
        }
        response {
            code(HttpStatusCode.OK) { description = "Withdrawal operation status"; body<BankWithdrawalOperationStatus>() }
            code(HttpStatusCode.NotFound) { description = "Withdrawal operation not found" }
        }
    }) {
        val uuid = call.uuidPath("wopid")
        val params = StatusParams.extract(call.request.queryParameters)
        val op = db.withdrawal.pollStatus(
            uuid, 
            params,
            ctx.wireMethod,
            ctx.maxAmount 
        )?.copy(
            card_fees = ctx.wireTransferFees,
            min_amount = ctx.minAmount
        ) ?: throw notFound(
            "Withdrawal operation '$uuid' not found", 
            TalerErrorCode.BANK_TRANSACTION_NOT_FOUND
        )
        call.respond(op.copy(
            suggested_exchange = ctx.suggestedWithdrawalExchange,
            confirm_transfer_url = if (op.status == WithdrawalStatus.pending || op.status == WithdrawalStatus.selected) ctx.withdrawConfirmUrl(uuid) else null
        ))
    }
    post("/taler-integration/withdrawal-operation/{wopid}", {
        operationId = "selectWithdrawalExchange"
        description = "Select exchange and reserve for withdrawal"
        tags = listOf("Bank Integration")
        request {
            pathParameter<String>("wopid") { description = "Withdrawal operation ID" }
            body<BankWithdrawalOperationPostRequest>()
        }
        response {
            code(HttpStatusCode.OK) { description = "Exchange selected"; body<BankWithdrawalOperationPostResponse>() }
            code(HttpStatusCode.NotFound) { description = "Withdrawal operation not found" }
            code(HttpStatusCode.Conflict) { description = "Operation conflict" }
        }
    }) {
        val uuid = call.uuidPath("wopid")
        val req = call.receive<BankWithdrawalOperationPostRequest>()
        req.amount?.run(ctx::checkRegionalCurrency)
        val res = db.withdrawal.setDetails(
            uuid,
            req.selected_exchange,
            req.reserve_pub,
            req.amount,
            ctx.wireTransferFees,
            ctx.minAmount,
            ctx.maxAmount
        )
        
        when (res) {
            WithdrawalSelectionResult.UnknownOperation -> throw notFound(
                "Withdrawal operation '$uuid' not found", 
                TalerErrorCode.BANK_TRANSACTION_NOT_FOUND
            )
            WithdrawalSelectionResult.AlreadySelected -> throw conflict(
                "Cannot select different exchange and reserve pub. under the same withdrawal operation",
                TalerErrorCode.BANK_WITHDRAWAL_OPERATION_RESERVE_SELECTION_CONFLICT
            )
            WithdrawalSelectionResult.ReservePubReuse -> throw conflict(
                "Reserve pub already used", 
                TalerErrorCode.BANK_DUPLICATE_RESERVE_PUB_SUBJECT
            )
            WithdrawalSelectionResult.UnknownAccount -> throw conflict(
                "Account ${req.selected_exchange} not found",
                TalerErrorCode.BANK_UNKNOWN_ACCOUNT
            )
            WithdrawalSelectionResult.AccountIsNotExchange -> throw notExchange(req.selected_exchange.toString())
            WithdrawalSelectionResult.AmountDiffers -> throw conflict(
                "Given amount is different from the current",
                TalerErrorCode.BANK_AMOUNT_DIFFERS
            )
            WithdrawalSelectionResult.BalanceInsufficient -> throw conflict(
                "Insufficient funds",
                TalerErrorCode.BANK_UNALLOWED_DEBIT
            )
            WithdrawalSelectionResult.BadAmount -> throw conflict(
                "Amount either to high or too low",
                TalerErrorCode.BANK_UNALLOWED_DEBIT
            )
            WithdrawalSelectionResult.AlreadyAborted -> throw conflict(
                "Cannot update an aborted withdrawal",
                TalerErrorCode.BANK_UPDATE_ABORT_CONFLICT
            )
            is WithdrawalSelectionResult.Success -> {
                call.respond(BankWithdrawalOperationPostResponse(
                    transfer_done = res.status == WithdrawalStatus.confirmed, 
                    status = res.status,
                    confirm_transfer_url = if (res.status == WithdrawalStatus.pending || res.status == WithdrawalStatus.selected) ctx.withdrawConfirmUrl(uuid) else null
                ))
            }
        }
    }
    post("/taler-integration/withdrawal-operation/{wopid}/abort", {
        operationId = "abortIntegrationWithdrawal"
        description = "Abort a withdrawal operation"
        tags = listOf("Bank Integration")
        request {
            pathParameter<String>("wopid") { description = "Withdrawal operation ID" }
        }
        response {
            code(HttpStatusCode.NoContent) { description = "Withdrawal aborted successfully" }
            code(HttpStatusCode.NotFound) { description = "Withdrawal operation not found" }
            code(HttpStatusCode.Conflict) { description = "Cannot abort confirmed withdrawal" }
        }
    }) {
        val uuid = call.uuidPath("wopid")
        when (db.withdrawal.abort(uuid)) {
            AbortResult.UnknownOperation -> throw notFound(
                "Withdrawal operation '$uuid' not found",
                TalerErrorCode.BANK_TRANSACTION_NOT_FOUND
            )
            AbortResult.AlreadyConfirmed -> throw conflict(
                "Cannot abort confirmed withdrawal", 
                TalerErrorCode.BANK_ABORT_CONFIRM_CONFLICT
            )
            AbortResult.Success -> call.respond(HttpStatusCode.NoContent)
        }
    }
}