import { NextResponse } from "next/server" import { fetchMutation } from "convex/nextjs" import { api } from "@/convex/_generated/api" import { requireGhlSyncAuth } from "@/app/api/internal/ghl/shared" import { fetchGhlMessages } from "@/lib/server/ghl-sync" export async function POST(request: Request) { const authError = await requireGhlSyncAuth(request) if (authError) { return authError } try { const body = await request.json().catch(() => ({})) const providedItems = Array.isArray(body.items) ? body.items : null const fetched = providedItems ? { items: providedItems, nextCursor: typeof body.nextCursor === "string" ? body.nextCursor : undefined, } : await fetchGhlMessages({ limit: typeof body.limit === "number" ? body.limit : undefined, cursor: body.cursor ? String(body.cursor) : undefined, channel: body.channel === "Call" ? "Call" : "SMS", }) const grouped = new Map() for (const item of fetched.items) { const conversationId = String(item.conversationId || item.id || "") if (!conversationId || grouped.has(conversationId)) { continue } grouped.set(conversationId, item) } let imported = 0 for (const [entityId, item] of grouped.entries()) { await fetchMutation(api.crm.importConversation, { provider: "ghl", entityId, payload: item, }) imported += 1 } await fetchMutation(api.crm.updateSyncCheckpoint, { provider: "ghl", entityType: "conversations", entityId: "conversations", cursor: fetched.nextCursor, status: "synced", metadata: JSON.stringify({ imported, }), }) return NextResponse.json({ success: true, imported, nextCursor: fetched.nextCursor, }) } catch (error) { console.error("Failed to sync GHL conversations:", error) return NextResponse.json( { error: "Failed to sync GHL conversations" }, { status: 500 } ) } }