import type { components } from '$lib/generated/api';
import { createTypeahead } from '$lib/shared/hooks/useTypeahead.svelte';
import { formatDocumentDate, type DatePrecision } from '$lib/shared/utils/documentDate';
import { getLocale } from '$lib/paraglide/runtime.js';

type DocumentListItem = components['schemas']['DocumentListItem'];

export type DocumentOption = Pick<
	DocumentListItem,
	'id' | 'title' | 'documentDate' | 'metaDatePrecision' | 'metaDateEnd'
>;

export function createDocumentTypeahead() {
	return createTypeahead<DocumentOption>({
		fetchUrl: (q) =>
			fetch(`/api/documents/search?q=${encodeURIComponent(q)}&size=10`)
				.then((r) => {
					// Without this check a 401/500 parses as JSON without `items` and
					// renders as "no results" — errors must reach the hook's error state.
					if (!r.ok) throw new Error(`document search failed: ${r.status}`);
					return r.json();
				})
				.then((b: { items: DocumentListItem[] }) =>
					b.items.map((it) => ({
						id: it.id,
						title: it.title,
						documentDate: it.documentDate,
						metaDatePrecision: it.metaDatePrecision,
						metaDateEnd: it.metaDateEnd
					}))
				)
	});
}

export function formatDocumentOption(doc: DocumentOption): string {
	if (!doc.documentDate) return doc.title;
	const label = formatDocumentDate(
		doc.documentDate,
		doc.metaDatePrecision as DatePrecision,
		doc.metaDateEnd,
		null,
		getLocale()
	);
	return `${doc.title} · ${label}`;
}
