// backend/internal/fs.go
package internal

import (
	"errors"
	"os"
	"path/filepath"
	"strings"
)

func SafeJoin(root, rel string) (string, error) {
	rel = strings.TrimPrefix(rel, "/")
	p := filepath.Join(root, rel)
	ap, err := filepath.Abs(p)
	if err != nil {
		return "", err
	}
	ar, err := filepath.Abs(root)
	if err != nil {
		return "", err
	}
	if !strings.HasPrefix(ap, ar+string(os.PathSeparator)) && ap != ar {
		return "", errors.New("path escapes root")
	}
	return ap, nil
}
