package secrets

import (
	"os"
	"testing"
)

// TestInfisicalBackendConnect requires INFISICAL_SITE_URL env var.
// This is an integration test — skip if no Infisical instance is available.
func TestInfisicalBackendConnect(t *testing.T) {
	siteURL := os.Getenv("INFISICAL_SITE_URL")
	if siteURL == "" {
		t.Skip("INFISICAL_SITE_URL not set — skipping Infisical integration test")
	}

	cfg := InfisicalConfig{
		SiteURL:  siteURL,
		ClientID: os.Getenv("INFISICAL_CLIENT_ID"),
		ClientSecret: os.Getenv("INFISICAL_CLIENT_SECRET"),
		ProjectID:    os.Getenv("INFISICAL_PROJECT_ID"),
		SecretPath:   "/",
		Env:          "dev",
	}

	backend := NewInfisicalBackend(cfg)

	_, err := backend.List(t.Context())
	if err != nil {
		t.Logf("connect test: %v (expected if no secrets exist yet)", err)
	} else {
		t.Log("connected and listed secrets")
	}
}

// TestInfisicalBackendSetGet exercises the write-then-read flow.
func TestInfisicalBackendSetGet(t *testing.T) {
	if os.Getenv("INFISICAL_SITE_URL") == "" {
		t.Skip("INFISICAL_SITE_URL not set")
	}

	cfg := InfisicalConfig{
		SiteURL:      os.Getenv("INFISICAL_SITE_URL"),
		ClientID:     os.Getenv("INFISICAL_CLIENT_ID"),
		ClientSecret: os.Getenv("INFISICAL_CLIENT_SECRET"),
		ProjectID:    os.Getenv("INFISICAL_PROJECT_ID"),
		SecretPath:   "/",
		Env:          "dev",
	}

	backend := NewInfisicalBackend(cfg)

	testKey := "_oikos_test_phase5"
	testValue := "test-value-1"

	// Write
	if err := backend.Set(t.Context(), testKey, testValue); err != nil {
		t.Fatalf("Set: %v", err)
	}

	// Read back
	val, err := backend.Get(t.Context(), testKey)
	if err != nil {
		t.Fatalf("Get: %v", err)
	}
	if val != testValue {
		t.Errorf("got %q, want %q", val, testValue)
	}

	t.Logf("set/get round-trip OK: %s", testKey)
}
