import type { Database } from "bun:sqlite";
import type { EventBus } from "./eventbus";
import type { ThreadSummary, Message } from "./notmuch";
import { insertThread, insertMessage } from "../db/index";

export function syncThreadsToCache(
	db: Database,
	bus: EventBus,
	accountId: string,
	threads: ThreadSummary[],
	messagesMap: Map<string, Message[]>,
): void {
	const transaction = db.transaction(() => {
		for (const thread of threads) {
			insertThread(db, {
				threadId: thread.threadId,
				subject: thread.subject,
				authors: thread.authors,
				totalMessages: thread.totalMessages,
				tags: thread.tags.join(","),
				timestamp: thread.timestamp,
				accountId,
			});

			const messages = messagesMap.get(thread.threadId) ?? [];
			for (const msg of messages) {
				insertMessage(db, {
					messageId: msg.messageId,
					threadId: thread.threadId,
					fromHeader: msg.from,
					toHeader: msg.to,
					subject: msg.subject,
					date: msg.date,
					inReplyTo: msg.inReplyTo,
					body: msg.body,
					tags: msg.tags.join(","),
					timestamp: msg.timestamp,
					accountId,
				});
			}
		}
	});

	transaction();

	bus.publish({
		type: "threads_updated",
		accountId,
		threadCount: threads.length,
	});
}
