const INVALID_FILENAME_CHARS = /[^a-zA-Z0-9._-]/g;

export function sanitizeFileName(fileName: string) {
  const dotIndex = fileName.lastIndexOf('.');
  const baseName = dotIndex >= 0 ? fileName.slice(0, dotIndex) : fileName;
  const extension = dotIndex >= 0 ? fileName.slice(dotIndex).toLowerCase() : '';

  const safeBaseName = baseName
    .trim()
    .replace(/\s+/g, '-')
    .replace(INVALID_FILENAME_CHARS, '-')
    .replace(/-+/g, '-')
    .replace(/^-|-$/g, '') || 'file';

  return `${safeBaseName}${extension}`;
}

export function buildSourceFilePath(batchId: string, fileName: string) {
  const safeBatchId = batchId.trim().replace(/\s+/g, '-').replace(INVALID_FILENAME_CHARS, '-');
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
  const uuid = crypto.randomUUID();

  return `${safeBatchId}/${timestamp}-${uuid}-${sanitizeFileName(fileName)}`;
}

export function formatFileSize(sizeBytes: number) {
  if (!Number.isFinite(sizeBytes) || sizeBytes < 0) return '-';
  if (sizeBytes < 1024) return `${sizeBytes} B`;
  if (sizeBytes < 1024 * 1024) return `${(sizeBytes / 1024).toFixed(1)} KB`;
  if (sizeBytes < 1024 * 1024 * 1024) return `${(sizeBytes / (1024 * 1024)).toFixed(1)} MB`;

  return `${(sizeBytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
}