package agent

import (
	"testing"
)

func TestValidatePath(t *testing.T) {
	tests := []struct {
		name    string
		service string
		path    string
		want    string
		wantErr bool
	}{
		{
			name:    "valid simple path",
			service: "mcr",
			path:    "mcr.toml",
			want:    "/srv/mcr/mcr.toml",
		},
		{
			name:    "valid nested path",
			service: "mcr",
			path:    "certs/cert.pem",
			want:    "/srv/mcr/certs/cert.pem",
		},
		{
			name:    "reject traversal",
			service: "mcr",
			path:    "../etc/passwd",
			wantErr: true,
		},
		{
			name:    "reject absolute path",
			service: "mcr",
			path:    "/etc/passwd",
			wantErr: true,
		},
		{
			name:    "reject empty service",
			service: "",
			path:    "mcr.toml",
			wantErr: true,
		},
		{
			name:    "reject empty path",
			service: "mcr",
			path:    "",
			wantErr: true,
		},
		{
			name:    "reject double dot in middle",
			service: "mcr",
			path:    "certs/../../etc/passwd",
			wantErr: true,
		},
		{
			name:    "valid deeply nested",
			service: "metacrypt",
			path:    "data/keys/primary.key",
			want:    "/srv/metacrypt/data/keys/primary.key",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := validatePath(tt.service, tt.path)
			if tt.wantErr {
				if err == nil {
					t.Fatalf("expected error, got path %q", got)
				}
				return
			}
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}
			if got != tt.want {
				t.Errorf("got %q, want %q", got, tt.want)
			}
		})
	}
}
