package api

import (
	"fmt"
	"path/filepath"
	"regexp"
)

// validWorkspaceID matches the identifiers Laravel assigns to a workspace —
// project UUIDs and session IDs: letters, digits, underscore, hyphen. It
// deliberately excludes '.', '/' and '\\' so a value such as ".." or
// "../logs" can never escape the workspaces root through filepath.Join in any
// handler. Gin's router already forbids '/' in a single path segment, but a
// bare ".." segment (or an attacker-supplied JSON WorkspaceID) would otherwise
// resolve to the parent of the workspaces root.
var validWorkspaceID = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)

// safeWorkspacePath validates an untrusted workspace/session identifier and
// joins it to the workspaces root. It returns an error when the id is empty or
// contains anything outside the allowed identifier characters.
func (s *Server) safeWorkspacePath(id string) (string, error) {
	if !validWorkspaceID.MatchString(id) {
		return "", fmt.Errorf("invalid workspace id")
	}

	return filepath.Join(s.workspacePath, id), nil
}
