import { Hono } from "hono";
import type { Database } from "bun:sqlite";
import type { EventBus } from "../services/eventbus";
import { syncAndIndex } from "../services/orchestrator";
import { searchThreads, getThread } from "../services/notmuch";
import { syncThreadsToCache } from "../services/cache-sync";

export function syncRoutes(db: Database, bus: EventBus): Hono {
	const router = new Hono();

	router.post("/sync", async (c) => {
		const { accountId, channelName } = await c.req.json<{
			accountId: string;
			channelName: string;
		}>();

		const syncResult = await syncAndIndex(channelName);
		if (syncResult.exitCode !== 0) {
			return c.json({
				error: "sync failed",
				stderr: syncResult.stderr,
			}, 500);
		}

		const threads = await searchThreads("tag:inbox");

		const messagesMap = new Map<string, Awaited<ReturnType<typeof getThread>>>();
		for (const thread of threads) {
			const messages = await getThread(thread.threadId);
			messagesMap.set(thread.threadId, messages);
		}

		syncThreadsToCache(db, bus, accountId, threads, messagesMap);

		return c.json({
			status: "ok",
			threadsProcessed: threads.length,
		});
	});

	return router;
}
