/**
 * Allowlist of orthopaedic journals surfaced on /studies.
 *
 * Values are the canonical PubMed journal abbreviations (the `Title
 * Abbreviation` field shown on any PubMed record) — these are what the
 * `[Journal]` search field matches against. Using the abbreviation form
 * yields a cleaner esearch query than the full title and avoids punctuation
 * issues.
 *
 * The `label` is what we render in the UI (journal pill and filter dropdown).
 * It is intentionally shorter / marketing-friendly where the PubMed abbrev is
 * cryptic (e.g. "Spine (Phila Pa 1976)" → "Spine").
 */

export type Journal = {
  /** PubMed abbreviation used inside the `[Journal]` search field. */
  pubmed: string;
  /** Short human label shown in UI. */
  label: string;
};

export const ORTHO_JOURNALS: readonly Journal[] = [
  { pubmed: "J Bone Joint Surg Am", label: "JBJS Am" },
  { pubmed: "Bone Joint J", label: "JBJS Br" },
  { pubmed: "Am J Sports Med", label: "Am J Sports Med" },
  { pubmed: "Arthroscopy", label: "Arthroscopy" },
  { pubmed: "Clin Orthop Relat Res", label: "Clin Orthop Relat Res" },
  { pubmed: "Spine (Phila Pa 1976)", label: "Spine" },
  { pubmed: "Foot Ankle Int", label: "Foot Ankle Int" },
  { pubmed: "Orthop J Sports Med", label: "Orthop J Sports Med" },
  { pubmed: "J Orthop Res", label: "J Orthop Res" },
  { pubmed: "Osteoarthritis Cartilage", label: "Osteoarthritis Cartilage" },
  { pubmed: "Knee Surg Sports Traumatol Arthrosc", label: "KSSTA" },
  { pubmed: "J Shoulder Elbow Surg", label: "J Shoulder Elbow Surg" },
] as const;

/**
 * Build the esearch `term` parameter from the allowlist.
 *
 * Produces:
 *   ("J Bone Joint Surg Am"[Journal] OR "Bone Joint J"[Journal] OR …)
 *   AND ("last 180 days"[PDat])
 *
 * The `last N days` relative date works in PubMed and spares us from having
 * to compute explicit date ranges on the client.
 */
export function buildEsearchTerm(lastDays = 180): string {
  const journalClause = ORTHO_JOURNALS.map(
    (j) => `"${j.pubmed}"[Journal]`,
  ).join(" OR ");
  return `(${journalClause}) AND ("last ${lastDays} days"[PDat])`;
}

/**
 * Map PubMed's exact abbreviation back to our display label. Used by the
 * list page to render pretty pills without another fetch.
 */
export function labelForJournal(pubmedAbbrev: string): string {
  const hit = ORTHO_JOURNALS.find(
    (j) => j.pubmed.toLowerCase() === pubmedAbbrev.toLowerCase(),
  );
  return hit ? hit.label : pubmedAbbrev;
}
