//! Integration tests for mint-wallet interactions that should work across all mint implementations
//!
//! These tests verify the core functionality of the wallet-mint interaction protocol,
//! including minting, melting, and wallet restoration. They are designed to be
//! implementation-agnostic and should pass against any compliant Cashu mint,
//! including Nutshell, CDK, and other implementations that follow the Cashu NUTs.
//!
//! The tests use environment variables to determine which mint to connect to and
//! whether to use real Lightning Network payments (regtest mode) or simulated payments.

use core::panic;
use std::collections::HashMap;
use std::env;
use std::fmt::Debug;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;

use bip39::Mnemonic;
use cashu::{MeltRequest, PreMintSecrets};
use cdk::amount::{Amount, SplitTarget};
use cdk::mint_url::MintUrl;
use cdk::nuts::nut00::{KnownMethod, ProofsMethods};
use cdk::nuts::{CurrencyUnit, MeltQuoteState, NotificationPayload, PaymentMethod, State};
use cdk::wallet::{HttpClient, MintConnector, Wallet, WalletRepositoryBuilder};
use cdk_integration_tests::{create_invoice_for_env, get_mint_url_from_env, pay_if_regtest};
use cdk_sqlite::wallet::memory;
use futures::{SinkExt, StreamExt};
use lightning_invoice::Bolt11Invoice;
use serde_json::json;
use tokio::time::timeout;
use tokio_tungstenite::connect_async;
use tokio_tungstenite::tungstenite::protocol::Message;

// Helper function to get temp directory from environment or fallback
fn get_test_temp_dir() -> PathBuf {
    match env::var("CDK_ITESTS_DIR") {
        Ok(dir) => PathBuf::from(dir),
        Err(_) => panic!("Unknown test dir"),
    }
}

async fn get_notifications<T: StreamExt<Item = Result<Message, E>> + Unpin, E: Debug>(
    reader: &mut T,
    timeout_to_wait: Duration,
    total: usize,
) -> Vec<(String, NotificationPayload<String>)> {
    let mut results = Vec::new();
    for _ in 0..total {
        let msg = timeout(timeout_to_wait, reader.next())
            .await
            .expect("timeout")
            .unwrap()
            .unwrap();

        let mut response: serde_json::Value =
            serde_json::from_str(msg.to_text().unwrap()).expect("valid json");

        let mut params_raw = response
            .as_object_mut()
            .expect("object")
            .remove("params")
            .expect("valid params");

        let params_map = params_raw.as_object_mut().expect("params is object");

        results.push((
            params_map
                .remove("subId")
                .unwrap()
                .as_str()
                .unwrap()
                .to_string(),
            serde_json::from_value(params_map.remove("payload").unwrap()).unwrap(),
        ))
    }
    results
}

/// Tests a complete mint-melt round trip with WebSocket notifications
///
/// This test verifies the full lifecycle of tokens:
/// 1. Creates a mint quote and pays the invoice
/// 2. Mints tokens and verifies the correct amount
/// 3. Creates a melt quote to spend tokens
/// 4. Subscribes to WebSocket notifications for the melt process
/// 5. Executes the melt and verifies the payment was successful
/// 6. Validates all WebSocket notifications received during the process
///
/// This ensures the entire mint-melt flow works correctly and that
/// WebSocket notifications are properly sent at each state transition.
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_happy_mint_melt_round_trip() {
    let wallet = Wallet::new(
        &get_mint_url_from_env(),
        CurrencyUnit::Sat,
        Arc::new(memory::empty().await.unwrap()),
        Mnemonic::generate(12).unwrap().to_seed_normalized(""),
        None,
    )
    .expect("failed to create new wallet");

    let (ws_stream, _) = connect_async(format!(
        "{}/v1/ws",
        get_mint_url_from_env().replace("http", "ws")
    ))
    .await
    .expect("Failed to connect");
    let (mut write, mut reader) = ws_stream.split();

    let mint_quote = wallet
        .mint_quote(PaymentMethod::BOLT11, Some(100.into()), None, None)
        .await
        .unwrap();

    let invoice = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
    pay_if_regtest(&get_test_temp_dir(), &invoice)
        .await
        .unwrap();

    let proofs = wallet
        .wait_and_mint_quote(
            mint_quote.clone(),
            SplitTarget::default(),
            None,
            tokio::time::Duration::from_secs(60),
        )
        .await
        .expect("payment");

    let mint_amount = proofs.total_amount().unwrap();

    assert!(mint_amount == 100.into());

    let invoice = create_invoice_for_env(Some(50)).await.unwrap();

    let melt = wallet
        .melt_quote(
            PaymentMethod::Known(KnownMethod::Bolt11),
            invoice.to_string(),
            None,
            None,
        )
        .await
        .unwrap();

    write
        .send(Message::Text(
            serde_json::to_string(&json!({
                    "jsonrpc": "2.0",
                    "id": 2,
                    "method": "subscribe",
                    "params": {
                      "kind": "bolt11_melt_quote",
                      "filters": [
                        melt.id.clone(),
                      ],
                      "subId": "test-sub",
                    }

            }))
            .unwrap()
            .into(),
        ))
        .await
        .unwrap();

    // Parse both JSON strings to objects and compare them instead of comparing strings directly
    let binding = reader.next().await.unwrap().unwrap();
    let response_str = binding.to_text().unwrap();

    let response_json: serde_json::Value =
        serde_json::from_str(response_str).expect("Valid JSON response");
    let expected_json: serde_json::Value = serde_json::from_str(
        r#"{"jsonrpc":"2.0","result":{"status":"OK","subId":"test-sub"},"id":2}"#,
    )
    .expect("Valid JSON expected");

    assert_eq!(response_json, expected_json);

    // Read the initial state notification before starting the melt to ensure we capture Unpaid
    let initial_notification =
        get_notifications(&mut reader, Duration::from_millis(15000), 1).await;
    let (sub_id, payload) = &initial_notification[0];
    assert_eq!("test-sub", sub_id);
    let initial_melt = match payload {
        NotificationPayload::MeltQuoteBolt11Response(m) => m,
        _ => panic!("Wrong payload"),
    };
    assert_eq!(initial_melt.state, MeltQuoteState::Unpaid);
    assert_eq!(initial_melt.quote.to_string(), melt.id);

    // Now start the melt
    let mut metadata = HashMap::new();
    metadata.insert("test".to_string(), "value".to_string());

    let prepared = wallet
        .prepare_melt(&melt.id, metadata.clone())
        .await
        .unwrap();
    let melt_response = prepared.confirm().await.unwrap();
    assert!(melt_response.payment_proof().is_some());
    assert_eq!(melt_response.state(), MeltQuoteState::Paid);

    let txs = wallet.list_transactions(None).await.unwrap();
    let tx = txs
        .into_iter()
        .find(|tx| tx.quote_id == Some(melt.id.clone()))
        .unwrap();
    assert_eq!(tx.amount, melt.amount);
    assert_eq!(tx.metadata, metadata);

    // Read remaining notifications (Pending -> Paid)
    let notifications = get_notifications(&mut reader, Duration::from_millis(15000), 2).await;

    let (sub_id, payload) = &notifications[0];
    assert_eq!("test-sub", sub_id);
    let pending_melt = match payload {
        NotificationPayload::MeltQuoteBolt11Response(m) => m,
        _ => panic!("Wrong payload"),
    };
    assert_eq!(pending_melt.state, MeltQuoteState::Pending);
    assert_eq!(pending_melt.quote.to_string(), melt.id);

    let (sub_id, payload) = &notifications[1];
    assert_eq!("test-sub", sub_id);
    let final_melt = match payload {
        NotificationPayload::MeltQuoteBolt11Response(m) => m,
        _ => panic!("Wrong payload"),
    };
    assert_eq!(final_melt.state, MeltQuoteState::Paid);
    assert_eq!(final_melt.amount, 50.into());
    assert_eq!(final_melt.quote.to_string(), melt.id);
}

/// Tests basic minting functionality with payment verification
///
/// This test focuses on the core minting process:
/// 1. Creates a mint quote for a specific amount (100 sats)
/// 2. Verifies the quote has the correct amount
/// 3. Pays the invoice (or simulates payment in non-regtest environments)
/// 4. Waits for the mint to recognize the payment
/// 5. Mints tokens and verifies the correct amount was received
///
/// This ensures the basic minting flow works correctly from quote to token issuance.
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_happy_mint() {
    let wallet = Wallet::new(
        &get_mint_url_from_env(),
        CurrencyUnit::Sat,
        Arc::new(memory::empty().await.unwrap()),
        Mnemonic::generate(12).unwrap().to_seed_normalized(""),
        None,
    )
    .expect("failed to create new wallet");

    let mint_amount = Amount::from(100);

    let mint_quote = wallet
        .mint_quote(PaymentMethod::BOLT11, Some(mint_amount), None, None)
        .await
        .unwrap();

    assert_eq!(mint_quote.amount, Some(mint_amount));

    let invoice = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
    pay_if_regtest(&get_test_temp_dir(), &invoice)
        .await
        .unwrap();

    let proofs = wallet
        .wait_and_mint_quote(
            mint_quote.clone(),
            SplitTarget::default(),
            None,
            tokio::time::Duration::from_secs(60),
        )
        .await
        .expect("payment");

    let mint_amount = proofs.total_amount().unwrap();

    assert!(mint_amount == 100.into());
}

/// Tests wallet restoration and proof state verification
///
/// This test verifies the wallet restoration process:
/// 1. Creates a wallet with a specific seed and mints tokens
/// 2. Verifies the wallet has the expected balance
/// 3. Creates a new wallet instance with the same seed but empty storage
/// 4. Confirms the new wallet starts with zero balance
/// 5. Restores the wallet state from the mint
/// 6. Swaps the proofs to ensure they're valid
/// 7. Verifies the restored wallet has the correct balance
/// 8. Checks that the original proofs are now marked as spent
///
/// This ensures wallet restoration works correctly and that
/// the mint properly tracks spent proofs across wallet instances.
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_restore() {
    let seed = Mnemonic::generate(12).unwrap().to_seed_normalized("");
    let wallet = Wallet::new(
        &get_mint_url_from_env(),
        CurrencyUnit::Sat,
        Arc::new(memory::empty().await.unwrap()),
        seed,
        None,
    )
    .expect("failed to create new wallet");

    let mint_quote = wallet
        .mint_quote(PaymentMethod::BOLT11, Some(100.into()), None, None)
        .await
        .unwrap();

    let invoice = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
    pay_if_regtest(&get_test_temp_dir(), &invoice)
        .await
        .unwrap();

    let _proofs = wallet
        .wait_and_mint_quote(
            mint_quote.clone(),
            SplitTarget::default(),
            None,
            tokio::time::Duration::from_secs(60),
        )
        .await
        .expect("payment");

    assert_eq!(wallet.total_balance().await.unwrap(), 100.into());

    let wallet_2 = Wallet::new(
        &get_mint_url_from_env(),
        CurrencyUnit::Sat,
        Arc::new(memory::empty().await.unwrap()),
        seed,
        None,
    )
    .expect("failed to create new wallet");

    assert_eq!(wallet_2.total_balance().await.unwrap(), 0.into());

    let restored = wallet_2.restore().await.unwrap();
    let proofs = wallet_2.get_unspent_proofs().await.unwrap();

    assert!(!proofs.is_empty());

    let expected_fee = wallet.get_proofs_fee(&proofs).await.unwrap().total;
    wallet_2
        .swap(None, SplitTarget::default(), proofs, None, false)
        .await
        .unwrap();

    assert_eq!(restored.unspent, 100.into());

    // Since we have to do a swap we expect to restore amount - fee
    assert_eq!(
        wallet_2.total_balance().await.unwrap(),
        Amount::from(100) - expected_fee
    );

    let proofs = wallet.get_unspent_proofs().await.unwrap();

    let states = wallet.check_proofs_spent(proofs).await.unwrap();

    for state in states {
        if state.state != State::Spent {
            panic!("All proofs should be spent");
        }
    }
}

/// Tests wallet restoration with a large number of proofs (3000)
///
/// This test verifies the restore process works correctly with many proofs,
/// which is important for testing database performance (especially PostgreSQL)
/// and ensuring the restore batching logic handles large proof sets:
/// 1. Creates a wallet and mints 3000 sats as individual 1-sat proofs
/// 2. Creates a new wallet instance with the same seed but empty storage
/// 3. Restores the wallet state from the mint (requires ~30 restore batches)
/// 4. Verifies all 3000 proofs are correctly restored
/// 5. Swaps the proofs to ensure they're valid
/// 6. Checks that the original proofs are now marked as spent
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_restore_large_proof_count() {
    let seed = Mnemonic::generate(12).unwrap().to_seed_normalized("");
    let wallet = Wallet::new(
        &get_mint_url_from_env(),
        CurrencyUnit::Sat,
        Arc::new(memory::empty().await.unwrap()),
        seed,
        None,
    )
    .expect("failed to create new wallet");

    let mint_amount: u64 = 3000;
    let batch_size: u64 = 999; // Keep under 1000 outputs per request

    // Mint in batches to avoid exceeding the 1000 output limit per request
    let mut total_proofs = 0usize;
    let mut remaining = mint_amount;

    while remaining > 0 {
        let batch = remaining.min(batch_size);

        let mint_quote = wallet
            .mint_quote(PaymentMethod::BOLT11, Some(batch.into()), None, None)
            .await
            .unwrap();

        let invoice = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
        pay_if_regtest(&get_test_temp_dir(), &invoice)
            .await
            .unwrap();

        // Mint with SplitTarget::Value(1) to create individual 1-sat proofs
        let proofs = wallet
            .wait_and_mint_quote(
                mint_quote.clone(),
                SplitTarget::Value(1.into()),
                None,
                tokio::time::Duration::from_secs(120),
            )
            .await
            .expect("payment");

        total_proofs += proofs.len();
        remaining -= batch;
    }

    assert_eq!(total_proofs, mint_amount as usize);
    assert_eq!(wallet.total_balance().await.unwrap(), mint_amount.into());

    let wallet_2 = Wallet::new(
        &get_mint_url_from_env(),
        CurrencyUnit::Sat,
        Arc::new(memory::empty().await.unwrap()),
        seed,
        None,
    )
    .expect("failed to create new wallet");

    assert_eq!(wallet_2.total_balance().await.unwrap(), 0.into());

    let restored = wallet_2.restore().await.unwrap();
    let proofs = wallet_2.get_unspent_proofs().await.unwrap();

    assert_eq!(proofs.len(), mint_amount as usize);
    assert_eq!(restored.unspent, mint_amount.into());

    // Swap in batches to avoid exceeding the 1000 input limit per request
    let mut total_fee = Amount::ZERO;
    for batch in proofs.chunks(batch_size as usize) {
        let batch_vec = batch.to_vec();
        let batch_fee = wallet_2.get_proofs_fee(&batch_vec).await.unwrap().total;
        total_fee += batch_fee;
        wallet_2
            .swap(None, SplitTarget::default(), batch.to_vec(), None, false)
            .await
            .unwrap();
    }

    // Since we have to do a swap we expect to restore amount - fee
    assert_eq!(
        wallet_2.total_balance().await.unwrap(),
        Amount::from(mint_amount) - total_fee
    );

    let proofs = wallet.get_unspent_proofs().await.unwrap();

    // Check proofs in batches to avoid large queries
    for batch in proofs.chunks(100) {
        let states = wallet.check_proofs_spent(batch.to_vec()).await.unwrap();
        for state in states {
            if state.state != State::Spent {
                panic!("All proofs should be spent");
            }
        }
    }
}

/// Tests that wallet restore correctly handles non-sequential counter values
///
/// This test verifies that after restoring a wallet where there were gaps in the
/// counter sequence (e.g., due to failed operations or multi-device usage), the
/// wallet can continue to operate without errors.
///
/// Test scenario:
/// 1. Wallet mints proofs using counters 0-N
/// 2. Counter is incremented to simulate failed operations that consumed counter values
/// 3. Wallet mints more proofs using counters at higher values
/// 4. New wallet restores from seed and finds proofs at non-sequential counter positions
/// 5. Wallet should be able to continue normal operations (swaps) after restore
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_restore_with_counter_gap() {
    let seed = Mnemonic::generate(12).unwrap().to_seed_normalized("");
    let wallet = Wallet::new(
        &get_mint_url_from_env(),
        CurrencyUnit::Sat,
        Arc::new(memory::empty().await.unwrap()),
        seed,
        None,
    )
    .expect("failed to create new wallet");

    // Mint first batch of proofs (uses counters starting at 0)
    let mint_quote = wallet
        .mint_quote(PaymentMethod::BOLT11, Some(100.into()), None, None)
        .await
        .unwrap();
    let invoice = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
    pay_if_regtest(&get_test_temp_dir(), &invoice)
        .await
        .unwrap();

    let _proofs1 = wallet
        .wait_and_mint_quote(
            mint_quote.clone(),
            SplitTarget::default(),
            None,
            tokio::time::Duration::from_secs(60),
        )
        .await
        .expect("first mint failed");

    assert_eq!(wallet.total_balance().await.unwrap(), 100.into());

    // Get the active keyset ID to increment counter
    let active_keyset = wallet.fetch_active_keyset().await.unwrap();
    let keyset_id = active_keyset.id;

    // Create a gap in the counter sequence
    // This simulates failed operations or multi-device usage where counter values
    // were consumed but no signatures were obtained
    let gap_size = 50u32;
    wallet
        .localstore
        .increment_keyset_counter(&keyset_id, gap_size)
        .await
        .unwrap();

    // Mint second batch of proofs (uses counters after the gap)
    let mint_quote2 = wallet
        .mint_quote(PaymentMethod::BOLT11, Some(100.into()), None, None)
        .await
        .unwrap();
    let invoice2 = Bolt11Invoice::from_str(&mint_quote2.request).unwrap();
    pay_if_regtest(&get_test_temp_dir(), &invoice2)
        .await
        .unwrap();

    let _proofs2 = wallet
        .wait_and_mint_quote(
            mint_quote2.clone(),
            SplitTarget::default(),
            None,
            tokio::time::Duration::from_secs(60),
        )
        .await
        .expect("second mint failed");

    assert_eq!(wallet.total_balance().await.unwrap(), 200.into());

    // Create a new wallet with the same seed (simulating wallet restore scenario)
    let wallet_restored = Wallet::new(
        &get_mint_url_from_env(),
        CurrencyUnit::Sat,
        Arc::new(memory::empty().await.unwrap()),
        seed,
        None,
    )
    .expect("failed to create restored wallet");

    assert_eq!(wallet_restored.total_balance().await.unwrap(), 0.into());

    // Restore the wallet - this should find proofs at non-sequential counter positions
    let restored = wallet_restored.restore().await.unwrap();
    assert_eq!(restored.unspent, 200.into());

    let proofs = wallet_restored.get_unspent_proofs().await.unwrap();
    assert!(!proofs.is_empty());

    // Swap the restored proofs to verify they are valid
    let expected_fee = wallet_restored.get_proofs_fee(&proofs).await.unwrap().total;
    wallet_restored
        .swap(None, SplitTarget::default(), proofs, None, false)
        .await
        .expect("first swap after restore failed");

    let balance_after_first_swap = Amount::from(200) - expected_fee;
    assert_eq!(
        wallet_restored.total_balance().await.unwrap(),
        balance_after_first_swap
    );

    // Perform multiple swaps to verify the wallet can continue operating
    // after restore with non-sequential counter values
    for i in 0..gap_size {
        let proofs = wallet_restored.get_unspent_proofs().await.unwrap();
        if proofs.is_empty() {
            break;
        }

        let swap_result = wallet_restored
            .swap(None, SplitTarget::default(), proofs.clone(), None, false)
            .await;

        match swap_result {
            Ok(_) => {
                // Swap succeeded, continue
            }
            Err(e) => {
                let error_str = format!("{:?}", e);
                if error_str.contains("BlindedMessageAlreadySigned") {
                    panic!(
                        "Got 'blinded message already signed' error on swap {} after restore. \
                         Counter was not correctly set after restoring with non-sequential values.",
                        i + 1
                    );
                } else {
                    // Some other error - might be expected (e.g., insufficient funds due to fees)
                    break;
                }
            }
        }
    }
}

/// Tests that the melt quote status can be checked after a melt has completed
///
/// This test verifies:
/// 1. Mint tokens
/// 2. Create a melt quote and execute the melt
/// 3. Check the melt quote status via the wallet
/// 4. Verify the quote is in the Paid state
///
/// This ensures the mint correctly reports the melt quote status after completion.
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_melt_quote_status_after_melt() {
    let wallet = Wallet::new(
        &get_mint_url_from_env(),
        CurrencyUnit::Sat,
        Arc::new(memory::empty().await.unwrap()),
        Mnemonic::generate(12).unwrap().to_seed_normalized(""),
        None,
    )
    .expect("failed to create new wallet");

    let mint_quote = wallet
        .mint_quote(PaymentMethod::BOLT11, Some(100.into()), None, None)
        .await
        .unwrap();

    let invoice = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
    pay_if_regtest(&get_test_temp_dir(), &invoice)
        .await
        .unwrap();

    let proofs = wallet
        .wait_and_mint_quote(
            mint_quote.clone(),
            SplitTarget::default(),
            None,
            tokio::time::Duration::from_secs(60),
        )
        .await
        .expect("mint failed");

    let mint_amount = proofs.total_amount().unwrap();
    assert_eq!(mint_amount, 100.into());

    let invoice = create_invoice_for_env(Some(50)).await.unwrap();

    let melt_quote = wallet
        .melt_quote(
            PaymentMethod::Known(KnownMethod::Bolt11),
            invoice.to_string(),
            None,
            None,
        )
        .await
        .unwrap();

    let prepared = wallet
        .prepare_melt(&melt_quote.id, std::collections::HashMap::new())
        .await
        .unwrap();
    let melt_response = prepared.confirm().await.unwrap();
    assert_eq!(melt_response.state(), MeltQuoteState::Paid);

    let quote_status = wallet
        .check_melt_quote_status(&melt_quote.id)
        .await
        .unwrap();
    assert_eq!(
        quote_status.state,
        MeltQuoteState::Paid,
        "Melt quote should be in Paid state after successful melt"
    );

    let db_quote = wallet
        .localstore
        .get_melt_quote(&melt_quote.id)
        .await
        .unwrap()
        .unwrap();

    assert_eq!(
        db_quote.state,
        MeltQuoteState::Paid,
        "Melt quote should be in Paid state after successful melt"
    );
}

/// Tests that the melt quote status can be checked via WalletRepository after a melt has completed
///
/// This test verifies the same flow as test_melt_quote_status_after_melt but using
/// the WalletRepository abstraction:
/// 1. Create a WalletRepository and add a mint
/// 2. Mint tokens via the wallet repository
/// 3. Create a melt quote and execute the melt
/// 4. Check the melt quote status via check_melt_quote
/// 5. Verify the quote is in the Paid state
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_melt_quote_status_after_melt_wallet_repository() {
    let seed = Mnemonic::generate(12).unwrap().to_seed_normalized("");
    let localstore = Arc::new(memory::empty().await.unwrap());

    let wallet_repository = WalletRepositoryBuilder::new()
        .localstore(localstore.clone())
        .seed(seed)
        .build()
        .await
        .expect("failed to create wallet repository");

    let mint_url = MintUrl::from_str(&get_mint_url_from_env()).expect("invalid mint url");
    wallet_repository
        .add_wallet(mint_url.clone())
        .await
        .expect("failed to add mint");

    // Get the wallet from the repository to call methods directly
    let wallet = wallet_repository
        .get_wallet(&mint_url, &CurrencyUnit::Sat)
        .await
        .expect("failed to get wallet");

    let mint_quote = wallet
        .mint_quote(
            PaymentMethod::Known(KnownMethod::Bolt11),
            Some(100.into()),
            None,
            None,
        )
        .await
        .unwrap();

    let invoice = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
    pay_if_regtest(&get_test_temp_dir(), &invoice)
        .await
        .unwrap();

    let _proofs = wallet
        .wait_and_mint_quote(
            mint_quote.clone(),
            SplitTarget::default(),
            None,
            Duration::from_secs(60),
        )
        .await
        .expect("mint failed");

    let balances = wallet_repository.total_balance().await.unwrap();
    let balance = balances
        .get(&CurrencyUnit::Sat)
        .copied()
        .unwrap_or(Amount::ZERO);
    assert_eq!(balance, 100.into());

    let invoice = create_invoice_for_env(Some(50)).await.unwrap();

    let melt_quote = wallet
        .melt_quote(
            PaymentMethod::Known(KnownMethod::Bolt11),
            invoice.to_string(),
            None,
            None,
        )
        .await
        .unwrap();

    let melt_response: cdk::types::FinalizedMelt = wallet
        .prepare_melt(&melt_quote.id, HashMap::new())
        .await
        .unwrap()
        .confirm()
        .await
        .unwrap();
    assert_eq!(melt_response.state(), MeltQuoteState::Paid);

    let quote_status = wallet
        .check_melt_quote_status(&melt_quote.id)
        .await
        .unwrap();
    assert_eq!(
        quote_status.state,
        MeltQuoteState::Paid,
        "Melt quote should be in Paid state after successful melt (via WalletRepository)"
    );

    use cdk_common::database::WalletDatabase;

    let db_quote = localstore
        .get_melt_quote(&melt_quote.id)
        .await
        .unwrap()
        .unwrap();

    assert_eq!(
        db_quote.state,
        MeltQuoteState::Paid,
        "Melt quote should be in Paid state after successful melt"
    );
}

/// Tests that change outputs in a melt quote are correctly handled
///
/// This test verifies the following workflow:
/// 1. Mint 100 sats of tokens
/// 2. Create a melt quote for 9 sats (which requires 100 sats input with 91 sats change)
/// 3. Manually construct a melt request with proofs and blinded messages for change
/// 4. Verify that the change proofs in the response match what's reported by the quote status
///
/// This ensures the mint correctly processes change outputs during melting operations
/// and that the wallet can properly verify the change amounts match expectations.
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_fake_melt_change_in_quote() {
    let wallet = Wallet::new(
        &get_mint_url_from_env(),
        CurrencyUnit::Sat,
        Arc::new(memory::empty().await.unwrap()),
        Mnemonic::generate(12).unwrap().to_seed_normalized(""),
        None,
    )
    .expect("failed to create new wallet");

    let mint_quote = wallet
        .mint_quote(PaymentMethod::BOLT11, Some(100.into()), None, None)
        .await
        .unwrap();

    let bolt11 = Bolt11Invoice::from_str(&mint_quote.request).unwrap();

    pay_if_regtest(&get_test_temp_dir(), &bolt11).await.unwrap();

    let _proofs = wallet
        .wait_and_mint_quote(
            mint_quote.clone(),
            SplitTarget::default(),
            None,
            tokio::time::Duration::from_secs(60),
        )
        .await
        .expect("payment");

    let invoice = create_invoice_for_env(Some(9)).await.unwrap();

    let proofs = wallet.get_unspent_proofs().await.unwrap();

    let melt_quote = wallet
        .melt_quote(
            PaymentMethod::Known(KnownMethod::Bolt11),
            invoice.to_string(),
            None,
            None,
        )
        .await
        .unwrap();

    let keyset = wallet.fetch_active_keyset().await.unwrap();
    let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();

    let premint_secrets = PreMintSecrets::random(
        keyset.id,
        100.into(),
        &SplitTarget::default(),
        &fee_and_amounts,
    )
    .unwrap();

    let client = HttpClient::new(get_mint_url_from_env().parse().unwrap(), None);

    let melt_request = MeltRequest::new(
        melt_quote.id.clone(),
        proofs.clone(),
        Some(premint_secrets.blinded_messages()),
    );

    let melt_response = client
        .post_melt(&PaymentMethod::Known(KnownMethod::Bolt11), melt_request)
        .await
        .unwrap();

    assert!(melt_response.change.is_some());

    let check = client.get_melt_quote_status(&melt_quote.id).await.unwrap();
    let mut melt_change = melt_response.change.unwrap();
    melt_change.sort_by(|a, b| a.amount.cmp(&b.amount));

    let mut check = check.change.unwrap();
    check.sort_by(|a, b| a.amount.cmp(&b.amount));

    assert_eq!(melt_change, check);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_pay_invoice_twice() {
    let ln_backend = match env::var("LN_BACKEND") {
        Ok(val) => Some(val),
        Err(_) => env::var("CDK_MINTD_LN_BACKEND").ok(),
    };

    if ln_backend.map(|ln| ln.to_uppercase()) == Some("FAKEWALLET".to_string()) {
        // We can only perform this test on regtest backends as fake wallet just marks the quote as paid
        return;
    }

    let wallet = Wallet::new(
        &get_mint_url_from_env(),
        CurrencyUnit::Sat,
        Arc::new(memory::empty().await.unwrap()),
        Mnemonic::generate(12).unwrap().to_seed_normalized(""),
        None,
    )
    .expect("failed to create new wallet");

    let mint_quote = wallet
        .mint_quote(PaymentMethod::BOLT11, Some(100.into()), None, None)
        .await
        .unwrap();

    pay_if_regtest(&get_test_temp_dir(), &mint_quote.request.parse().unwrap())
        .await
        .unwrap();

    let proofs = wallet
        .wait_and_mint_quote(
            mint_quote.clone(),
            SplitTarget::default(),
            None,
            tokio::time::Duration::from_secs(60),
        )
        .await
        .expect("payment");

    let mint_amount = proofs.total_amount().unwrap();

    assert_eq!(mint_amount, 100.into());

    let invoice = create_invoice_for_env(Some(25)).await.unwrap();

    let melt_quote = wallet
        .melt_quote(
            PaymentMethod::Known(KnownMethod::Bolt11),
            invoice.to_string(),
            None,
            None,
        )
        .await
        .unwrap();

    let prepared = wallet
        .prepare_melt(&melt_quote.id, std::collections::HashMap::new())
        .await
        .unwrap();
    let melt = prepared.confirm().await.unwrap();

    // Creating a second quote for the same invoice is allowed
    let melt_quote_two = wallet
        .melt_quote(
            PaymentMethod::Known(KnownMethod::Bolt11),
            invoice.to_string(),
            None,
            None,
        )
        .await
        .unwrap();

    // But attempting to melt (pay) the second quote should fail
    // since the first quote with the same lookup_id is already paid
    let melt_two = async {
        let prepared = wallet
            .prepare_melt(&melt_quote_two.id, std::collections::HashMap::new())
            .await?;
        prepared.confirm().await
    }
    .await;

    match melt_two {
        Err(err) => {
            let err_str = err.to_string().to_lowercase();
            if !err_str.contains("duplicate")
                && !err_str.contains("already paid")
                && !err_str.contains("request already paid")
            {
                panic!(
                    "Expected duplicate/already paid error, got: {}",
                    err.to_string()
                );
            }
        }
        Ok(_) => {
            panic!("Should not have allowed second payment");
        }
    }

    let balance = wallet.total_balance().await.unwrap();

    assert_eq!(
        balance,
        (Amount::from(100) - melt.fee_paid() - melt.amount())
    );
}
