//go:build integration

package steme

import (
	"context"
	"fmt"
	"os"
	"testing"
	"time"
)

// Integration test helpers and health check.
//
// To run these tests:
//
//  1. Start the StemeDB API server:
//     cargo run --bin stemedb-api
//
//  2. Run the integration tests:
//     STEMEDB_URL=http://localhost:18180 go test -tags=integration ./...
//
// These tests are skipped by default (build tag "integration") to avoid
// breaking CI when no server is running.

// getTestClient creates a client with a generated signer for testing.
//
// Skips the test if STEMEDB_URL is not set.
func getTestClient(t *testing.T) *Client {
	t.Helper()

	baseURL := os.Getenv("STEMEDB_URL")
	if baseURL == "" {
		t.Skip("STEMEDB_URL not set - skipping integration test")
	}

	signer, err := GenerateSigner()
	if err != nil {
		t.Fatalf("GenerateSigner() failed: %v", err)
	}

	return NewClient(baseURL, signer)
}

// uniqueSubject generates a unique subject for test isolation.
//
// This prevents tests from interfering with each other by ensuring
// each test operates on distinct subjects.
func uniqueSubject(base string) string {
	return fmt.Sprintf("%s_%d", base, time.Now().UnixNano())
}

// TestIntegration_Health verifies the health endpoint works.
func TestIntegration_Health(t *testing.T) {
	client := getTestClient(t)
	ctx := context.Background()

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

	if health.Status != "healthy" {
		t.Errorf("Health.Status = %s, want healthy", health.Status)
	}

	if health.Version == "" {
		t.Error("Health.Version is empty")
	}

	t.Logf("Server status: %s, version: %s, assertions: %d",
		health.Status, health.Version, health.AssertionsCount)
}
