package apimart

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestBalanceUsesConfiguredBaseURLAndAPIKey(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
		if request.URL.Path != "/v1/user/balance" {
			t.Fatalf("unexpected path: %s", request.URL.Path)
		}
		if request.Header.Get("Authorization") != "Bearer test-key" {
			t.Fatalf("unexpected authorization header: %s", request.Header.Get("Authorization"))
		}
		fmt.Fprint(response, `{"success":true,"remain_balance":10.5,"remain_credits":105.25,"used_balance":2.3,"used_credits":2005.21388,"unlimited_quota":false}`)
	}))
	defer server.Close()

	result, err := NewClient(server.Client()).Balance(context.Background(), server.URL+"/v1", "test-key")
	if err != nil {
		t.Fatalf("Balance returned error: %v", err)
	}
	if result.RemainBalance != 10.5 || result.RemainCredits != 105.25 || result.UsedBalance != 2.3 || result.UsedCredits != 2005.21388 || result.UnlimitedQuota {
		t.Fatalf("unexpected result: %#v", result)
	}
}

func TestBalanceReturnsUpstreamMessage(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, _ *http.Request) {
		fmt.Fprint(response, `{"success":false,"message":"record not found"}`)
	}))
	defer server.Close()

	_, err := NewClient(server.Client()).Balance(context.Background(), server.URL, "test-key")
	if err == nil || err.Error() != "record not found" {
		t.Fatalf("expected upstream message, got %v", err)
	}
}
