// Pure URL rewrite for relative markdown image paths in FilePreview.
//
// Extracted (behavior-preserving) from `components/files/FilePreview.tsx`'s
// markdown image renderer so the rewrite can be unit-tested without a DOM.
// MUST stay byte-for-byte equivalent to the inline logic it replaced:
//   - http(s) and data: URIs pass through untouched
//   - a falsy href passes through untouched
//   - any other (relative / root-relative) href gets a leading `./` stripped,
//     is URL-encoded as a single path component, then prefixed with imageBaseUrl

/** True for hrefs that must NOT be rewritten (absolute web URLs / inline data). */
function isAbsoluteOrDataHref(href: string): boolean {
  return (
    href.startsWith('http://') ||
    href.startsWith('https://') ||
    href.startsWith('data:')
  );
}

/**
 * Rewrite a markdown image `src` to point at the workspace raw-file endpoint.
 *
 * @param href          the raw `src` from the markdown image token
 * @param imageBaseUrl  prefix for relative paths, e.g.
 *                      `/api/local/tasks/123/files/raw?path=`. When falsy, the
 *                      href is returned unchanged (matches the component, which
 *                      only installs the custom renderer when a base URL exists).
 * @returns the resolved href. Absolute/data/empty hrefs are returned unchanged.
 */
export function resolvePreviewImageHref(
  href: string | null | undefined,
  imageBaseUrl: string | null | undefined,
): string {
  const src = href ?? '';
  // No base URL → the component never rewrites; return the href as-is.
  if (!imageBaseUrl) return src;
  // Falsy href or absolute/data URI → leave untouched.
  if (!src || isAbsoluteOrDataHref(src)) return src;
  const cleanPath = src.replace(/^\.\//, '');
  return `${imageBaseUrl}${encodeURIComponent(cleanPath)}`;
}
