package infra

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

func TestSSHConfigRead_Missing(t *testing.T) {
	t.Setenv("HOME", t.TempDir())
	entries, err := SSHConfigRead()
	if err != nil {
		t.Fatalf("expected nil error for missing config, got %v", err)
	}
	if entries != nil {
		t.Errorf("expected nil entries, got %+v", entries)
	}
}

func TestSSHConfigRead_ParsesExisting(t *testing.T) {
	home := t.TempDir()
	t.Setenv("HOME", home)
	sshDir := filepath.Join(home, ".ssh")
	if err := os.MkdirAll(sshDir, 0700); err != nil {
		t.Fatal(err)
	}
	content := `Host prod
    HostName 10.0.0.1
    User admin
    Port 2222
`
	if err := os.WriteFile(filepath.Join(sshDir, "config"), []byte(content), 0600); err != nil {
		t.Fatal(err)
	}
	entries, err := SSHConfigRead()
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if len(entries) != 1 {
		t.Fatalf("expected 1 entry, got %d", len(entries))
	}
	if entries[0].Alias != "prod" || entries[0].HostName != "10.0.0.1" || entries[0].User != "admin" || entries[0].Port != 2222 {
		t.Errorf("unexpected entry: %+v", entries[0])
	}
}

func TestSSHConfigRead_PermissionError(t *testing.T) {
	if os.Geteuid() == 0 {
		t.Skip("root bypasses permission errors")
	}
	home := t.TempDir()
	t.Setenv("HOME", home)
	sshDir := filepath.Join(home, ".ssh")
	if err := os.MkdirAll(sshDir, 0700); err != nil {
		t.Fatal(err)
	}
	configPath := filepath.Join(sshDir, "config")
	if err := os.WriteFile(configPath, []byte("Host x\n"), 0000); err != nil {
		t.Fatal(err)
	}
	defer os.Chmod(configPath, 0600)
	if _, err := SSHConfigRead(); err == nil {
		t.Error("expected error reading unreadable config")
	}
}
