import { BadRequestException } from '@nestjs/common';

export function assertSafeServerPath(path: string): string {
  const normalized = path.replace(/\\/g, '/').replace(/^\/+/, '');

  if (!normalized || normalized === '.') {
    return '.';
  }

  if (normalized.includes('\0')) {
    throw new BadRequestException('Invalid path');
  }

  const segments = normalized.split('/');
  if (segments.some((segment) => segment === '..' || segment === '')) {
    throw new BadRequestException('Path traversal is not allowed');
  }

  return normalized;
}
