package exploit

import "testing"

func TestParseCommand_Basic(t *testing.T) {
	args, err := parseCommand("nmap -sV --top-ports 100 1.2.3.4")
	if err != nil {
		t.Fatal(err)
	}
	want := []string{"nmap", "-sV", "--top-ports", "100", "1.2.3.4"}
	if len(args) != len(want) {
		t.Fatalf("got %v want %v", args, want)
	}
	for i := range args {
		if args[i] != want[i] {
			t.Fatalf("arg %d: got %q want %q", i, args[i], want[i])
		}
	}
}

func TestParseCommand_Quotes(t *testing.T) {
	args, err := parseCommand(`curl -H "User-Agent: swarm 1.0" https://example.com/a b`)
	if err != nil {
		t.Fatal(err)
	}
	want := []string{"curl", "-H", "User-Agent: swarm 1.0", "https://example.com/a", "b"}
	for i := range want {
		if args[i] != want[i] {
			t.Fatalf("arg %d: got %q want %q", i, args[i], want[i])
		}
	}
}

func TestParseCommand_RejectsShellMeta(t *testing.T) {
	cases := []string{
		"cat /etc/passwd | grep root",
		"nmap -sV 1.2.3.4 > out.txt",
		"whoami && id",
		"echo hi; rm -rf /",
		"echo `id`",
		"echo $(id)",
		"echo hi\nrm -rf /",
	}
	for _, c := range cases {
		if _, err := parseCommand(c); err == nil {
			t.Errorf("expected reject for %q", c)
		}
	}
}

func TestParseCommand_AllowsMetaInQuotes(t *testing.T) {
	// sh -c "echo a | grep b" is the documented escape hatch.
	args, err := parseCommand(`sh -c "echo a | grep b"`)
	if err != nil {
		t.Fatal(err)
	}
	if len(args) != 3 || args[2] != "echo a | grep b" {
		t.Fatalf("unexpected args: %v", args)
	}
}

func TestParseCommand_Empty(t *testing.T) {
	if _, err := parseCommand(""); err == nil {
		t.Fatal("expected error for empty command")
	}
	if _, err := parseCommand("   "); err == nil {
		t.Fatal("expected error for whitespace-only command")
	}
}

func TestParseCommand_UnterminatedQuote(t *testing.T) {
	if _, err := parseCommand(`curl "foo`); err == nil {
		t.Fatal("expected error for unterminated quote")
	}
}
