import 'server-only'; import { run, sql, safe } from '@/lib/db'; import type { ProvenanceInfo } from '@/components/ui/source-badge'; export interface ProvRow { id: number; source_id: string; source_slug: string; source_name: string; source_url: string | null; dataset: string | null; dataset_version: string | null; retrieved_at: Date; evidence_type: string; license: string | null; pmid: string | null; ingest_run_id: string | null; source_record_id: string | null; methodology: string | null; population: string | null; geography: string | null; } /** Load provenance rows (joined with the source) for a set of ids, keyed by id. */ export async function loadProvenance(ids: Array): Promise> { const uniq = [...new Set(ids.filter((i): i is number => typeof i === 'number' && Number.isFinite(i)))]; if (uniq.length === 0) return new Map(); const rows = await safe( () => run(sql` SELECT p.id, p.source_id, s.slug AS source_slug, s.name AS source_name, p.source_url, p.dataset, p.dataset_version, p.retrieved_at, p.evidence_type, coalesce(p.license, s.license) AS license, p.pmid, p.ingest_run_id, p.source_record_id, p.methodology, p.population, p.geography FROM provenance p JOIN sources s ON s.id = p.source_id WHERE p.id IN ${sql`(${sql.join(uniq.map((i) => sql`${i}`), sql`, `)})`}`), [] as ProvRow[], ); return new Map(rows.map((r) => [Number(r.id), r])); } export function toInfo(p: ProvRow | undefined, layer: ProvenanceInfo['layer'] = 'normalized'): ProvenanceInfo | null { if (!p) return null; return { sourceSlug: p.source_slug, sourceName: p.source_name, dataset: p.dataset, datasetVersion: p.dataset_version, retrievedAt: p.retrieved_at, sourceUrl: p.source_url, layer, license: p.license, evidenceType: p.evidence_type, pmid: p.pmid, ingestRunId: p.ingest_run_id, }; } /** Minimal source lookup for badges when only a source_id is known. */ export async function sourceInfoById(ids: Array): Promise> { const uniq = [...new Set(ids.filter((i): i is string => !!i))]; if (uniq.length === 0) return new Map(); const rows = await safe( () => run<{ id: string; slug: string; name: string; license: string | null }>(sql`SELECT id, slug, name, license FROM sources WHERE id IN (${sql.join(uniq.map((i) => sql`${i}`), sql`, `)})`), [] as Array<{ id: string; slug: string; name: string; license: string | null }>, ); return new Map(rows.map((r) => [r.id, { slug: r.slug, name: r.name, license: r.license }])); }