//go:build test && dev

package square

import (
	"context"
	"sync"
	"testing"
	"time"
)

func TestDevClient_CreatePayment_ReturnsCompleted(t *testing.T) {
	client := NewDevClient().(*MockClient)

	ctx := context.Background()
	req := CreatePaymentReq{
		Amount:         5000,
		Currency:       "GBP",
		SourceID:       "cnon:test-card",
		IdempotencyKey: "test-key-1",
		ReferenceID:    "booking-123",
		Note:           "full",
	}

	result, err := client.CreatePayment(ctx, req)
	if err != nil {
		t.Fatalf("CreatePayment failed: %v", err)
	}

	if result.Status != "COMPLETED" {
		t.Errorf("expected status COMPLETED, got %s", result.Status)
	}

	if result.Amount != 5000 {
		t.Errorf("expected amount 5000, got %d", result.Amount)
	}

	if result.CardBrand != "VISA" {
		t.Errorf("expected card brand VISA, got %s", result.CardBrand)
	}

	if result.CardLast4 != "4242" {
		t.Errorf("expected last4 4242, got %s", result.CardLast4)
	}

	if result.Fees == 0 {
		t.Error("expected fees to be calculated")
	}
}

func TestDevClient_CreateCheckout_PendingThenCompleted(t *testing.T) {
	client := NewDevClient().(*MockClient)

	ctx := context.Background()
	req := CreateCheckoutReq{
		Amount:         7500,
		Currency:       "GBP",
		IdempotencyKey: "checkout-key-1",
		ReferenceID:    "booking-456",
		TipEnabled:     true,
	}

	result, err := client.CreateCheckout(ctx, req)
	if err != nil {
		t.Fatalf("CreateCheckout failed: %v", err)
	}

	if result.Status != "PENDING" {
		t.Errorf("expected status PENDING, got %s", result.Status)
	}

	if result.ID == "" {
		t.Error("expected checkout ID to be set")
	}

	// Poll until the background goroutine completes — avoids any timing assumptions
	var completed *PaymentResult
	for i := 0; i < 20; i++ {
		completed, err = client.GetCheckout(ctx, result.ID)
		if err == nil && completed.Status == "COMPLETED" {
			break
		}
		time.Sleep(200 * time.Millisecond)
	}
	if err != nil {
		t.Fatalf("GetCheckout failed: %v", err)
	}

	if completed.Status != "COMPLETED" {
		t.Errorf("expected status COMPLETED, got %s", completed.Status)
	}

	if completed.Amount != 8000 {
		t.Errorf("expected amount 8000 (7500 + 500 tip), got %d", completed.Amount)
	}

	if completed.TipAmount != 500 {
		t.Errorf("expected tip 500, got %d", completed.TipAmount)
	}
}

func TestDevClient_CreateCheckout_NoTip(t *testing.T) {
	client := NewDevClient().(*MockClient)

	ctx := context.Background()
	req := CreateCheckoutReq{
		Amount:         5000,
		Currency:       "GBP",
		IdempotencyKey: "checkout-key-notip",
		ReferenceID:    "booking-789",
		TipEnabled:     false,
	}

	result, err := client.CreateCheckout(ctx, req)
	if err != nil {
		t.Fatalf("CreateCheckout failed: %v", err)
	}

	if result.Status != "PENDING" {
		t.Errorf("expected status PENDING, got %s", result.Status)
	}

	if result.ID == "" {
		t.Error("expected checkout ID to be set")
	}

	var completed *PaymentResult
	for i := 0; i < 20; i++ {
		completed, err = client.GetCheckout(ctx, result.ID)
		if err == nil && completed.Status == "COMPLETED" {
			break
		}
		time.Sleep(200 * time.Millisecond)
	}
	if err != nil {
		t.Fatalf("GetCheckout failed: %v", err)
	}

	if completed.Amount != 5000 {
		t.Errorf("expected amount 5000 (no tip), got %d", completed.Amount)
	}

	if completed.TipAmount != 0 {
		t.Errorf("expected tip 0, got %d", completed.TipAmount)
	}
}

func TestDevClient_RefundPayment_ReturnsCompleted(t *testing.T) {
	client := NewDevClient().(*MockClient)

	ctx := context.Background()

	paymentReq := CreatePaymentReq{
		Amount:         10000,
		Currency:       "GBP",
		SourceID:       "cnon:test-card",
		IdempotencyKey: "payment-for-refund",
		ReferenceID:    "booking-refund",
		Note:           "full",
	}

	paymentResult, err := client.CreatePayment(ctx, paymentReq)
	if err != nil {
		t.Fatalf("CreatePayment failed: %v", err)
	}

	refundReq := RefundPaymentReq{
		PaymentID:      paymentResult.ID,
		Amount:         5000,
		IdempotencyKey: "refund-key-1",
		Reason:         "customer request",
	}

	refundResult, err := client.RefundPayment(ctx, refundReq)
	if err != nil {
		t.Fatalf("RefundPayment failed: %v", err)
	}

	if refundResult.Status != "COMPLETED" {
		t.Errorf("expected status COMPLETED, got %s", refundResult.Status)
	}

	if refundResult.Amount != 5000 {
		t.Errorf("expected amount 5000, got %d", refundResult.Amount)
	}
}

func TestDevClient_CardOnFile_CreateAndGet(t *testing.T) {
	client := NewDevClient().(*MockClient)

	ctx := context.Background()
	userID := "user-test-123"

	card, err := client.CreateCardOnFile(ctx, userID, "cnon:test-token")
	if err != nil {
		t.Fatalf("CreateCardOnFile failed: %v", err)
	}

	if card.ID == "" {
		t.Error("expected card ID to be set")
	}

	if card.Brand != "VISA" {
		t.Errorf("expected brand VISA, got %s", card.Brand)
	}

	if card.Last4 != "4242" {
		t.Errorf("expected last4 4242, got %s", card.Last4)
	}

	if !card.IsDefault {
		t.Error("expected first card to be default")
	}

	cards, err := client.GetCardsOnFile(ctx, userID)
	if err != nil {
		t.Fatalf("GetCardsOnFile failed: %v", err)
	}

	if len(cards) != 1 {
		t.Errorf("expected 1 card, got %d", len(cards))
	}

	if cards[0].ID != card.ID {
		t.Errorf("expected card ID %s, got %s", card.ID, cards[0].ID)
	}
}

func TestDevClient_CardOnFile_MultipleCards(t *testing.T) {
	client := NewDevClient().(*MockClient)

	ctx := context.Background()
	userID := "user-test-multiple"

	card1, err := client.CreateCardOnFile(ctx, userID, "cnon:token-1")
	if err != nil {
		t.Fatalf("CreateCardOnFile failed: %v", err)
	}

	card2, err := client.CreateCardOnFile(ctx, userID, "cnon:token-2")
	if err != nil {
		t.Fatalf("CreateCardOnFile failed: %v", err)
	}

	cards, err := client.GetCardsOnFile(ctx, userID)
	if err != nil {
		t.Fatalf("GetCardsOnFile failed: %v", err)
	}

	if len(cards) != 2 {
		t.Errorf("expected 2 cards, got %d", len(cards))
	}

	if !card1.IsDefault {
		t.Error("first card should be default")
	}

	if card2.IsDefault {
		t.Error("second card should not be default")
	}
}

func TestDevClient_CardOnFile_Delete(t *testing.T) {
	client := NewDevClient().(*MockClient)

	ctx := context.Background()
	userID := "user-test-delete"

	card, err := client.CreateCardOnFile(ctx, userID, "cnon:token-delete")
	if err != nil {
		t.Fatalf("CreateCardOnFile failed: %v", err)
	}

	err = client.DeleteCardOnFile(ctx, card.ID)
	if err != nil {
		t.Fatalf("DeleteCardOnFile failed: %v", err)
	}

	cards, err := client.GetCardsOnFile(ctx, userID)
	if err != nil {
		t.Fatalf("GetCardsOnFile failed: %v", err)
	}

	if len(cards) != 0 {
		t.Errorf("expected 0 cards after delete, got %d", len(cards))
	}
}

func TestDevClient_CardOnFile_DeleteNotFound(t *testing.T) {
	client := NewDevClient().(*MockClient)

	ctx := context.Background()

	err := client.DeleteCardOnFile(ctx, "non-existent-card")
	if err == nil {
		t.Error("expected error when deleting non-existent card")
	}
}

func TestDevClient_GetCheckout_NotFound(t *testing.T) {
	client := NewDevClient().(*MockClient)

	ctx := context.Background()

	_, err := client.GetCheckout(ctx, "non-existent-checkout")
	if err == nil {
		t.Error("expected error when checkout not found")
	}
}

func TestDevClient_ConcurrentPayments(t *testing.T) {
	client := NewDevClient().(*MockClient)

	ctx := context.Background()
	var wg sync.WaitGroup
	results := make(chan *PaymentResult, 10)
	errors := make(chan error, 10)

	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func(idx int) {
			defer wg.Done()

			req := CreatePaymentReq{
				Amount:         int64(1000 + idx*100),
				Currency:       "GBP",
				SourceID:       "cnon:test-card",
				IdempotencyKey: "concurrent-key-" + string(rune('0'+idx)),
				ReferenceID:    "booking-concurrent",
				Note:           "full",
			}

			result, err := client.CreatePayment(ctx, req)
			if err != nil {
				errors <- err
				return
			}
			results <- result
		}(i)
	}

	wg.Wait()
	close(results)
	close(errors)

	errorCount := 0
	for err := range errors {
		t.Logf("Concurrent payment error: %v", err)
		errorCount++
	}

	if errorCount > 0 {
		t.Errorf("expected no errors, got %d", errorCount)
	}

	resultCount := 0
	for result := range results {
		if result.Status != "COMPLETED" {
			t.Errorf("expected status COMPLETED, got %s", result.Status)
		}
		resultCount++
	}

	if resultCount != 10 {
		t.Errorf("expected 10 results, got %d", resultCount)
	}
}
