import type { SearchResultPayload } from "./types.js";

export function buildSearchPayload(
  query: string,
  matches: SearchResultPayload["matches"],
): SearchResultPayload {
  return {
    query,
    returned: matches.length,
    matches,
  };
}

export function formatPayloadAsText(payload: SearchResultPayload): string {
  if (payload.matches.length === 0) {
    return `Brak wyników dla: ${payload.query}`;
  }

  const lines = [
    `Wyniki dla: ${payload.query}`,
    `Znalezione: ${payload.returned}`,
    "",
    ...payload.matches.map(formatMatch),
  ];

  return lines.join("\n");
}

function formatMatch(
  match: SearchResultPayload["matches"][number],
  index: number,
): string {
  const base = `${index + 1}. ${match.code} - ${match.text}`;
  if (match.matchType === "synonym" && match.synonymTerm) {
    return `${base} (przez synonim: "${match.synonymTerm}")`;
  }
  return base;
}
