// /api/offcloud/sync — status and configuration for the continuous auto-sync. // // GET -> config + live state + library counts // POST { ...config } -> update the auto-sync config // POST ?now=1 -> run one delta sync immediately // POST ?now=1&full=1 -> run a full reconcile immediately import { NextRequest, NextResponse } from "next/server"; import { getAutoSyncConfig, updateAutoSyncConfig, getSyncState, getLibraryCounts, startAutoSync, syncOnce, type AutoSyncConfig, } from "@/lib/sync-engine"; export const dynamic = "force-dynamic"; export const runtime = "nodejs"; async function payload() { const [config, counts] = await Promise.all([getAutoSyncConfig(), getLibraryCounts()]); return { config, state: getSyncState(), counts }; } export async function GET() { try { // Arm the loop if this process has not started it yet (e.g. the // instrumentation hook was skipped in a dev reload). await startAutoSync(); return NextResponse.json(await payload()); } catch (err) { const msg = err instanceof Error ? err.message : "Unknown error"; return NextResponse.json({ error: msg }, { status: 500 }); } } export async function POST(req: NextRequest) { const url = new URL(req.url); const now = url.searchParams.get("now"); const full = url.searchParams.get("full"); try { if (now) { const result = await syncOnce({ mode: full ? "full" : "delta", trigger: "manual", }); return NextResponse.json({ ok: !result.error, result, ...(await payload()) }); } const body = (await req.json().catch(() => ({}))) as Partial; const patch: Partial = {}; if (typeof body.enabled === "boolean") patch.enabled = body.enabled; if (body.intervalSeconds !== undefined) patch.intervalSeconds = Number(body.intervalSeconds); if (typeof body.fullSyncOnBoot === "boolean") patch.fullSyncOnBoot = body.fullSyncOnBoot; if (body.pruneAfterHours !== undefined) patch.pruneAfterHours = Number(body.pruneAfterHours); const config = await updateAutoSyncConfig(patch); return NextResponse.json({ ok: true, config, state: getSyncState() }); } catch (err) { const msg = err instanceof Error ? err.message : "Unknown error"; return NextResponse.json({ error: msg }, { status: 500 }); } }