import { NextRequest, NextResponse } from 'next/server'; import { assertCronAuth } from '@/lib/cron-auth'; import { syncAllGhlTenants } from '@/lib/gohighlevel-sync'; export const dynamic = 'force-dynamic'; export const maxDuration = 300; /** * Daily GoHighLevel reconciliation (upsert, no wipe). * Dokploy ~05:20 UTC: * curl -sS -H "Authorization: Bearer $CRON_SECRET" \ * "https://app.4ventures.es/api/cron/ghl-sync" */ export async function GET(req: NextRequest) { const denied = assertCronAuth(req); if (denied) return denied; const lookbackDays = Math.min( 120, Math.max(14, Number(req.nextUrl.searchParams.get('lookback')) || 60) ); const tenantId = req.nextUrl.searchParams.get('tenant_id') || undefined; try { const { results } = await syncAllGhlTenants({ tenantId, lookbackDays }); const withErrors = results.filter((r) => r.error); return NextResponse.json( { ok: withErrors.length === 0, at: new Date().toISOString(), lookbackDays, synced: results.filter((r) => !r.error).length, withErrors: withErrors.length, results, }, { status: withErrors.length ? 207 : 200 } ); } catch (e) { return NextResponse.json( { ok: false, error: e instanceof Error ? e.message : 'ghl-sync failed', }, { status: 500 } ); } } export async function POST(req: NextRequest) { return GET(req); }