import { formatDate } from '$lib/shared/utils/date';
import { m } from '$lib/paraglide/messages.js';
import { joinNameOrUnknown, unknownPersonName } from '$lib/person/personFormat';

type AuthorSummary = { firstName?: string; lastName?: string };
type DocumentMeta = { documentDate?: string; senderName?: string; receiverName?: string };
type AuthorView = { displayName: string };

export function formatAuthorName(author: AuthorSummary | null | undefined): string {
	if (!author) return '';
	// Email is no longer exposed — names or the localized fallback only.
	return joinNameOrUnknown(author.firstName, author.lastName);
}

export function formatAuthorDisplayName(author: AuthorView | null | undefined): string {
	if (!author) return '';
	// The server-side fallback is the literal '[Unbekannt]' — localize it here.
	return author.displayName === '[Unbekannt]' ? unknownPersonName() : author.displayName;
}

export function formatPublishedAt(
	publishedAt: string | null | undefined,
	style: 'short' | 'long' = 'short'
): string | null {
	if (!publishedAt) return null;
	return formatDate(publishedAt.slice(0, 10), style);
}

/** "12.07.1938 · von Franz an Emma" — shared by JourneyItemCard and the story doc-reference cards. */
export function formatDocumentMetaLine(doc: DocumentMeta): string {
	const parts: string[] = [];
	if (doc.documentDate) parts.push(formatDate(doc.documentDate, 'short'));
	if (doc.senderName && doc.receiverName) {
		parts.push(m.journey_item_meta_from_to({ sender: doc.senderName, receiver: doc.receiverName }));
	} else if (doc.senderName) {
		parts.push(doc.senderName);
	}
	return parts.join(' · ');
}
