package main

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

	"github.com/unkn0wn-root/resterm/internal/cli"
)

func TestLoadEnvironmentExplicitDotEnv(t *testing.T) {
	dir := t.TempDir()
	envPath := filepath.Join(dir, ".env.local")
	content := "workspace=local\nAPI_URL=http://localhost\n"
	if err := os.WriteFile(envPath, []byte(content), 0o644); err != nil {
		t.Fatalf("write env file: %v", err)
	}

	envs, resolved := cli.LoadEnvironment(envPath, "", dir)
	if resolved != envPath {
		t.Fatalf("resolved path = %q, want %q", resolved, envPath)
	}
	env := envs["local"]
	if env == nil {
		t.Fatalf("expected local environment, got %v", envs)
	}
	if env["API_URL"] != "http://localhost" {
		t.Fatalf("API_URL = %q, want %q", env["API_URL"], "http://localhost")
	}
}

func TestLoadEnvironmentIgnoresDotEnvDiscovery(t *testing.T) {
	dir := t.TempDir()
	envPath := filepath.Join(dir, ".env")
	if err := os.WriteFile(
		envPath,
		[]byte("workspace=dev\nAPI_URL=https://api\n"),
		0o644,
	); err != nil {
		t.Fatalf("write env file: %v", err)
	}

	envs, resolved := cli.LoadEnvironment("", "", dir)
	if envs != nil {
		t.Fatalf("expected no auto-discovered envs, got %v", envs)
	}
	if resolved != "" {
		t.Fatalf("resolved path = %q, want empty", resolved)
	}
}

func TestHandleInitSubcommandAmbiguousFile(t *testing.T) {
	dir := t.TempDir()
	cwd, err := os.Getwd()
	if err != nil {
		t.Fatalf("getwd: %v", err)
	}
	t.Cleanup(func() {
		_ = os.Chdir(cwd)
	})
	if err := os.Chdir(dir); err != nil {
		t.Fatalf("chdir: %v", err)
	}
	if err := os.WriteFile(filepath.Join(dir, "init"), []byte("data"), 0o644); err != nil {
		t.Fatalf("write file: %v", err)
	}

	handled, err := handleInitSubcommand([]string{"init"})
	if !handled {
		t.Fatalf("expected init to be handled")
	}
	if err == nil {
		t.Fatalf("expected ambiguity error")
	}
}

func TestRunInitListArgs(t *testing.T) {
	if err := runInit([]string{"--list", "extra"}); err == nil {
		t.Fatalf("expected error for extra args")
	}
}
