/**
 * Vancouver-style citation builder.
 *
 * Vancouver format (what NLM/ICMJE recommends) looks roughly like:
 *
 *   Smith AB, Jones CD, Lee EF, et al. Article title. J Bone Joint Surg.
 *   2026 Apr;108(4):123-130. doi:10.1000/xyz. PMID: 12345678.
 *
 * We don't have volume/issue/pages in the normalised `Study` shape (PubMed
 * does return them but we stripped them for list-page brevity), so we emit
 * the subset we do have — authors, title, journal, date, DOI, PMID. This is
 * still a valid Vancouver citation, just without the pagination.
 *
 * Up to 6 authors are listed in full, after which we append "et al." per
 * the NLM convention.
 */

import type { Study } from "./types";

function formatYearMonth(iso: string): string {
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return "";
  const year = d.getUTCFullYear();
  const month = d.toLocaleString("en-US", { month: "short", timeZone: "UTC" });
  return `${year} ${month}`;
}

export function buildVancouverCitation(study: Study): string {
  const parts: string[] = [];

  // Authors: up to 6, then "et al."
  if (study.authors.length > 0) {
    const head =
      study.authors.length > 6
        ? `${study.authors.slice(0, 6).join(", ")}, et al.`
        : `${study.authors.join(", ")}.`;
    parts.push(head);
  }

  // Title — Vancouver uses sentence case but we keep the title as PubMed
  // returns it (upstream decides casing).
  const title = study.title.trim().replace(/\.$/, "");
  parts.push(`${title}.`);

  // Journal + date
  const journal = study.journal?.trim();
  const ymd = formatYearMonth(study.pubDate);
  if (journal && ymd) {
    parts.push(`${journal}. ${ymd}.`);
  } else if (journal) {
    parts.push(`${journal}.`);
  } else if (ymd) {
    parts.push(`${ymd}.`);
  }

  if (study.doi) {
    parts.push(`doi:${study.doi}.`);
  }

  parts.push(`PMID: ${study.pmid}.`);

  return parts.join(" ").replace(/\s+/g, " ").trim();
}
