/**
 * Code link and reference builders for wiki pages.
 */

import type { WikiCodeReference } from "../types/wiki-model";
import { toRelativePath } from "./utils";

/* ------------------------------------------------------------------ */
/*  Code link builders                                                 */
/* ------------------------------------------------------------------ */

export function buildCodeHref(
  sourcePath: string,
  filePath: string,
  lineStart?: number,
  lineEnd?: number,
  symbol?: string,
): string {
  const params = new URLSearchParams({
    path: toRelativePath(sourcePath, filePath),
  });
  if (lineStart) params.set("line", String(lineStart));
  if (lineEnd) params.set("end", String(lineEnd));
  if (symbol) params.set("symbol", symbol);
  return `/__code__?${params.toString()}`;
}

export function buildCodeLink(
  label: string,
  sourcePath: string,
  filePath: string,
  lineStart?: number,
  lineEnd?: number,
  symbol?: string,
): string {
  return `[${label}](${buildCodeHref(sourcePath, filePath, lineStart, lineEnd, symbol)})`;
}

export function buildCodeReference(
  label: string,
  sourcePath: string,
  filePath: string,
  line?: number,
  endLine?: number,
  symbol?: string,
  nodeId?: string,
  relation?: string,
): WikiCodeReference {
  return {
    label,
    path: toRelativePath(sourcePath, filePath),
    line,
    endLine,
    symbol,
    nodeId,
    relation,
  };
}
