package cli

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

	"git.eeqj.de/sneak/secret/internal/secret"
	"github.com/spf13/afero"
)

func TestCLIInstanceStateDir(t *testing.T) {
	// Test the CLI instance state directory functionality
	fs := afero.NewMemMapFs()

	// Create a test state directory
	testStateDir := "/test-state-dir"
	cli := NewCLIInstanceWithStateDir(fs, testStateDir)

	if cli.GetStateDir() != testStateDir {
		t.Errorf("Expected state directory %q, got %q", testStateDir, cli.GetStateDir())
	}
}

func TestCLIInstanceWithFs(t *testing.T) {
	// Test creating CLI instance with custom filesystem
	fs := afero.NewMemMapFs()
	cli := NewCLIInstanceWithFs(fs)

	// The state directory should be determined automatically
	stateDir := cli.GetStateDir()
	if stateDir == "" {
		t.Error("Expected non-empty state directory")
	}
}

func TestDetermineStateDir(t *testing.T) {
	// Test the determineStateDir function from the secret package

	// Save original environment and restore it after test
	originalStateDir := os.Getenv(secret.EnvStateDir)
	defer func() {
		if originalStateDir == "" {
			os.Unsetenv(secret.EnvStateDir)
		} else {
			os.Setenv(secret.EnvStateDir, originalStateDir)
		}
	}()

	// Test with environment variable set
	testEnvDir := "/test-env-dir"
	os.Setenv(secret.EnvStateDir, testEnvDir)

	stateDir := secret.DetermineStateDir("")
	if stateDir != testEnvDir {
		t.Errorf("Expected state directory %q from environment, got %q", testEnvDir, stateDir)
	}

	// Test with custom config dir
	os.Unsetenv(secret.EnvStateDir)
	customConfigDir := "/custom-config"
	stateDir = secret.DetermineStateDir(customConfigDir)
	expectedDir := filepath.Join(customConfigDir, secret.AppID)
	if stateDir != expectedDir {
		t.Errorf("Expected state directory %q with custom config, got %q", expectedDir, stateDir)
	}
}
