package hbank

import (
	"context"
	"encoding/json"
	"errors"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"
)

func fake(t *testing.T, handler func(path string, body map[string]any) (int, string)) *Client {
	t.Helper()
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Header.Get("Authorization") != "Bearer test_key" {
			w.WriteHeader(http.StatusForbidden)
			io.WriteString(w, "Invalid API key")
			return
		}
		var body map[string]any
		_ = json.NewDecoder(r.Body).Decode(&body)
		status, text := handler(r.URL.RequestURI(), body)
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(status)
		io.WriteString(w, text)
	}))
	t.Cleanup(srv.Close)
	return New("test_key", WithBaseURL(srv.URL))
}

func TestCreatePaymentSendsAmountAsString(t *testing.T) {
	c := fake(t, func(path string, body map[string]any) (int, string) {
		if path != "/api/v1/payment/request" || body["amount"] != "24.90" || body["currency"] != "EUR" {
			t.Errorf("unexpected request %s %v", path, body)
		}
		if _, ok := body["description"]; ok {
			t.Errorf("empty description should be left out")
		}
		return 200, `{"success": true, "transaction_id": "tx_8fK2mQ7xRb4Tn9WcYz3LpH6v"}`
	})
	tid, err := c.CreatePayment(context.Background(), PaymentRequest{Amount: "24.90", Currency: "EUR"})
	if err != nil || tid != "tx_8fK2mQ7xRb4Tn9WcYz3LpH6v" {
		t.Fatalf("got %s, %v", tid, err)
	}
	if got := c.CheckoutURL(tid); !strings.HasSuffix(got, "/api/payment?tid=tx_8fK2mQ7xRb4Tn9WcYz3LpH6v") {
		t.Errorf("checkout url %s", got)
	}
}

func TestPaymentKeepsDigitsAndTimes(t *testing.T) {
	c := fake(t, func(path string, _ map[string]any) (int, string) {
		if strings.HasPrefix(path, "/api/v1/subscriptions/sub_Hk3Rt9WzQe5NcXa2LpVb7YdF") {
			return 200, `{"success": true, "subscription": {"id": "sub_Hk3Rt9WzQe5NcXa2LpVb7YdF", "status": "active", "amount": 9.99, "subscribed_at": "2026-10-03T09:12:44.1234567Z", "customer": {"name": "Ada"}}}`
		}
		return 200, `{"success": true, "transaction": {"id": "tx_8fK2mQ7xRb4Tn9WcYz3LpH6v", "amount": 24.90, "refunded": 0.00, "status": "completed"}}`
	})
	p, err := c.GetPayment(context.Background(), "tx_8fK2mQ7xRb4Tn9WcYz3LpH6v")
	if err != nil || p.Amount.String() != "24.90" || !p.Completed() {
		t.Fatalf("got %+v, %v", p, err)
	}
	s, err := c.GetSubscription(context.Background(), "sub_Hk3Rt9WzQe5NcXa2LpVb7YdF")
	if err != nil || s.SubscribedAt == nil || s.SubscribedAt.Nanosecond() != 123456700 || s.Customer.Name != "Ada" {
		t.Fatalf("got %+v, %v", s, err)
	}
}

func TestErrors(t *testing.T) {
	c := fake(t, func(string, map[string]any) (int, string) {
		return 409, `{"success": false, "error": "not_refundable", "message": "Already refunded."}`
	})
	_, err := c.Refund(context.Background(), "tx_8fK2mQ7xRb4Tn9WcYz3LpH6v", "", "")
	var e *Error
	if !errors.As(err, &e) || e.Code != "not_refundable" || e.Status != 409 || e.Message != "Already refunded." {
		t.Fatalf("got %v", err)
	}
	_, err = New("nope", WithBaseURL(c.BaseURL)).ListSubscriptions(context.Background())
	if !IsCode(err, "invalid_api_key") {
		t.Fatalf("got %v", err)
	}
	_, err = New("k", WithBaseURL("http://127.0.0.1:1")).Rate(context.Background(), "EUR", "USD")
	if !IsCode(err, "connection_failed") {
		t.Fatalf("got %v", err)
	}
}

func TestCallbackHandler(t *testing.T) {
	h := CallbackHandler(func(_ *http.Request, cb *Callback) (CallbackAnswer, error) {
		if cb.Amount.String() == "24.90" {
			return Approve(), nil
		}
		return Refuse("Wrong amount"), nil
	})
	for body, want := range map[string]string{
		`{"id": 1, "amount": 24.90, "currency": "EUR"}`: `{"resume":true}`,
		`{"id": 1, "amount": 5, "currency": "EUR"}`:     `{"resume":false,"error":"Wrong amount"}`,
		`{}`: `{"resume":false,"error":"Invalid callback"}`,
	} {
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/cb", strings.NewReader(body)))
		if rec.Code != 200 || strings.TrimSpace(rec.Body.String()) != want || rec.Header().Get("Content-Type") != "application/json" {
			t.Errorf("%s: got %d %s", body, rec.Code, rec.Body.String())
		}
	}
}

func TestVerifySignature(t *testing.T) {
	body := []byte(`{"id":7310,"amount":24.9,"currency":"EUR","status":"awaiting_approval","description":"Order 1042"}`)
	header := "t=1700000000,v1=fcfc30b9667c3a8e8aea68178c36716153e075f79c61521bf3586088d9877281"
	now := time.Unix(1700000100, 0)
	if !VerifySignature("hbcb_test", header, body, now) {
		t.Fatal("valid signature refused")
	}
	if VerifySignature("hbcb_other", header, body, now) || VerifySignature("hbcb_test", header, []byte("{}"), now) ||
		VerifySignature("hbcb_test", header, body, time.Unix(1700000400, 0)) || VerifySignature("hbcb_test", "garbage", body, now) {
		t.Fatal("invalid signature accepted")
	}
}

func TestSubscriptionsCheckoutSendsIdsAndOffers(t *testing.T) {
	c := fake(t, func(path string, body map[string]any) (int, string) {
		items, _ := body["subscriptions"].([]any)
		offer, _ := items[1].(map[string]any)
		if path != "/api/v1/subscriptions/checkout" || len(items) != 2 || items[0] != "sub_Hk3Rt9WzQe5NcXa2LpVb7YdF" ||
			offer["amount"] != "2.50" || offer["interval_count"] != float64(1) || body["callback_url"] != "https://shop.example/cb" {
			t.Errorf("unexpected request %s %v", path, body)
		}
		if _, ok := offer["callback_url"]; ok {
			t.Errorf("an offer carries no callback url")
		}
		if _, ok := body["description"]; ok {
			t.Errorf("empty description should be left out")
		}
		return 200, `{"success": true, "transaction_id": "tx_8fK2mQ7xRb4Tn9WcYz3LpH6v", "subscriptions": [{"id": "sub_Hk3Rt9WzQe5NcXa2LpVb7YdF"}, {"id": "sub_Q2"}]}`
	})
	out, err := c.CreateSubscriptionsCheckout(context.Background(), SubscriptionsCheckoutRequest{
		Subscriptions: []SubscriptionCheckoutItem{
			ExistingSubscription("sub_Hk3Rt9WzQe5NcXa2LpVb7YdF"),
			NewSubscription(SubscriptionRequest{Amount: "2.50", Currency: "EUR", Interval: "week", CallbackURL: "ignored"}),
		},
		CallbackURL: "https://shop.example/cb",
	})
	if err != nil || out.TransactionID != "tx_8fK2mQ7xRb4Tn9WcYz3LpH6v" || len(out.Subscriptions) != 2 || out.Subscriptions[1].ID != "sub_Q2" {
		t.Fatalf("got %+v, %v", out, err)
	}
}

func TestPaymentListsItsSubscriptions(t *testing.T) {
	c := fake(t, func(string, map[string]any) (int, string) {
		return 200, `{"success": true, "transaction": {"id": "tx_1", "amount": 7.50, "status": "completed", "subscription_id": null, "subscription_ids": ["sub_A", "sub_B"]}}`
	})
	p, err := c.GetPayment(context.Background(), "tx_1")
	if err != nil || len(p.SubscriptionIDs) != 2 || p.SubscriptionIDs[1] != "sub_B" || p.SubscriptionID != nil {
		t.Fatalf("got %+v, %v", p, err)
	}
}
