package bitcoin

import (
	"testing"
)

func TestGetAddressInfo(t *testing.T) {
	// Test with a known address from the test mnemonic
	testAddress := "1LqBGSKuX5yYUonjxT5qGfpUsXKYYWeabA"

	balance, txCount, received, sent, err := GetAddressInfo(testAddress)
	if err != nil {
		t.Fatalf("GetAddressInfo failed: %v", err)
	}

	// This address has been used in tests, so it should have transactions
	if txCount == 0 {
		t.Log("Warning: Test address has no transactions. This might be expected if blockchain state changed.")
	}

	// Balance should equal received - sent
	expectedBalance := received - sent
	if balance != expectedBalance {
		t.Errorf("Balance mismatch: balance=%d, received=%d, sent=%d, expected=%d",
			balance, received, sent, expectedBalance)
	}

	t.Logf("Address: %s", testAddress)
	t.Logf("Balance: %d satoshis (%.8f BTC)", balance, float64(balance)/100000000.0)
	t.Logf("Received: %d satoshis", received)
	t.Logf("Sent: %d satoshis", sent)
	t.Logf("Transactions: %d", txCount)
}

func TestGetTransactions(t *testing.T) {
	// Test with a known address from the test mnemonic
	testAddress := "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu"

	txs, err := GetTransactions(testAddress)
	if err != nil {
		t.Fatalf("GetTransactions failed: %v", err)
	}

	t.Logf("Found %d transactions for address %s", len(txs), testAddress)

	// Verify transaction structure
	for i, tx := range txs {
		if tx.TxID == "" {
			t.Errorf("Transaction %d has empty TxID", i)
		}

		if tx.Time.IsZero() && tx.Confirmed {
			t.Errorf("Transaction %d is confirmed but has zero time", i)
		}

		// At least one of Received or Sent should be non-zero
		if tx.Received == 0 && tx.Sent == 0 {
			t.Logf("Warning: Transaction %d has zero received and sent amounts", i)
		}

		t.Logf("  Tx %d: %s, Received: %d, Sent: %d, NetChange: %d, Time: %s",
			i, tx.TxID[:16], tx.Received, tx.Sent, tx.NetChange, tx.Time.Format("2006-01-02"))
	}
}

func TestGetAddressInfoInvalidAddress(t *testing.T) {
	// Test with an invalid address
	_, _, _, _, err := GetAddressInfo("invalid_address")
	if err == nil {
		t.Error("Expected error for invalid address, got nil")
	}
}
