// Data-import DOMAIN — the bucket-relative path validator. Pure. This single function enforces
// the SAME rule that appears under three IDs across the specs:
//   • C2  (data-import-spec.md:119)  — Cloud item paths start at the bucket, not a full URL.
//   • IL6 (items-list-spec.md)        — Items List item paths are storage-relative.
//   • V1  (data-import-spec.md:168)   — the sample-path field rejects URLs with guidance.
// Example valid:   `redbrick-bucket/project-2/brain-mri.dcm`
// Example invalid: `https://s3.amazonaws.com/redbrick-bucket/...`  (a full URL)

import { importError, type ImportError } from './types';

/**
 * A bucket-relative path: non-empty, not a URL, not absolute, no `..` traversal. The first
 * segment is the bucket name (`bucket/key…`). Returns true if `s` is acceptable.
 */
export function isBucketRelativePath(s: string): boolean {
  return bucketPathProblem(s) === null;
}

/**
 * Validate a single path, returning a located ImportError (code PATH_NOT_BUCKET_RELATIVE) or null.
 * `loc` lets the caller attach the offending Items List entry / file for per-row reporting (P2).
 */
export function validateBucketRelativePath(
  s: string,
  loc?: { entry?: string; file?: string },
): ImportError | null {
  const problem = bucketPathProblem(s);
  if (!problem) return null;
  return importError('PATH_NOT_BUCKET_RELATIVE', problem, loc ?? { file: s });
}

/** Returns a human (Vietnamese) reason the path is not bucket-relative, or null if it's fine. */
function bucketPathProblem(s: string): string | null {
  const path = s?.trim() ?? '';
  if (path === '') return 'Đường dẫn trống.';
  // A scheme (http://, https://, s3://, gs://, …) means a full URL — rejected.
  if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(path) || path.includes('://')) {
    return 'Phải là đường dẫn tương đối theo bucket (vd: my-bucket/folder/file.dcm), không phải URL đầy đủ.';
  }
  // Absolute paths and backslashes are not bucket-relative.
  if (path.startsWith('/') || path.startsWith('\\')) {
    return 'Đường dẫn không được bắt đầu bằng "/" — phải bắt đầu từ tên bucket.';
  }
  // No parent-directory traversal.
  if (path.split('/').some((seg) => seg === '..')) {
    return 'Đường dẫn không được chứa ".." (đi ngược thư mục).';
  }
  // Must have a bucket + at least one key segment.
  if (!path.includes('/') || path.endsWith('/')) {
    return 'Đường dẫn phải gồm tên bucket và khoá đối tượng (vd: my-bucket/file.dcm).';
  }
  return null;
}
