package infra

import (
	"os"
	"path/filepath"
	"testing"
)

func TestResolveRegistryRoot(t *testing.T) {
	t.Run("env var apunta a tmpdir con registry.db", func(t *testing.T) {
		dir := t.TempDir()
		dbPath := filepath.Join(dir, "registry.db")
		if err := os.WriteFile(dbPath, []byte("SQLite format 3\x00"), 0644); err != nil {
			t.Fatal(err)
		}
		t.Setenv("FN_REGISTRY_ROOT", dir)

		got, err := ResolveRegistryRoot()
		if err != nil {
			t.Fatalf("expected no error, got: %v", err)
		}
		if got != filepath.Clean(dir) {
			t.Errorf("got %q, want %q", got, filepath.Clean(dir))
		}
	})

	t.Run("HOME apunta a tmpdir con fn_registry/registry.db", func(t *testing.T) {
		homeDir := t.TempDir()
		registryDir := filepath.Join(homeDir, "fn_registry")
		if err := os.MkdirAll(registryDir, 0755); err != nil {
			t.Fatal(err)
		}
		dbPath := filepath.Join(registryDir, "registry.db")
		if err := os.WriteFile(dbPath, []byte("SQLite format 3\x00"), 0644); err != nil {
			t.Fatal(err)
		}
		// Clear env var so we fall through to the HOME check.
		t.Setenv("FN_REGISTRY_ROOT", "")
		t.Setenv("HOME", homeDir)

		got, err := ResolveRegistryRoot()
		if err != nil {
			t.Fatalf("expected no error, got: %v", err)
		}
		if got != registryDir {
			t.Errorf("got %q, want %q", got, registryDir)
		}
	})

	t.Run("nada existe devuelve error", func(t *testing.T) {
		emptyHome := t.TempDir()
		t.Setenv("FN_REGISTRY_ROOT", "")
		t.Setenv("HOME", emptyHome)

		_, err := ResolveRegistryRoot()
		if err == nil {
			t.Error("expected error when nothing exists, got nil")
		}
	})
}
