package src_test

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

// section: test
func Test_Chdir(t *testing.T) {
	// Get the original working directory
	original, err := os.Getwd()
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("Original directory: %s", original)

	// Create a temporary directory for the test
	tmpDir := t.TempDir()

	// Create a test file in the temporary directory
	testFile := filepath.Join(tmpDir, "test.txt")
	if err := os.WriteFile(testFile, []byte("hello"), 0644); err != nil {
		t.Fatal(err)
	}

	// Change to the temporary directory for this test
	t.Chdir(tmpDir)

	// Verify we're in the temp directory
	current, _ := os.Getwd()
	t.Logf("Changed to directory: %s", current)

	// Now we can use relative paths
	data, err := os.ReadFile("test.txt")
	if err != nil {
		t.Fatalf("failed to read file: %v", err)
	}

	if string(data) != "hello" {
		t.Errorf("expected 'hello', got '%s'", data)
	}

	t.Log("Successfully read file using relative path")
	// When the test ends, the working directory is automatically restored
}

// section: test

// section: config
func Test_ConfigFile(t *testing.T) {
	// Create a temporary directory with a config file
	tmpDir := t.TempDir()
	configPath := filepath.Join(tmpDir, "config.json")
	if err := os.WriteFile(configPath, []byte(`{"setting": "value"}`), 0644); err != nil {
		t.Fatal(err)
	}

	// Change to the directory
	t.Chdir(tmpDir)

	// Now code that looks for ./config.json will find it
	if _, err := os.Stat("config.json"); os.IsNotExist(err) {
		t.Error("config.json should exist in current directory")
	}

	t.Log("Found config.json in current directory")
}

// section: config
