import { NextRequest, NextResponse } from "next/server";
import { runGoogleBackfillForAllConnectedCalendars, pullGoogleChangesForAllConnectedCalendars } from "@/lib/googleSync";

// Wiederkehrendes Sicherheitsnetz (System-Crontab, alle 2 Stunden) — holt
// Termine nach, deren Push zuvor aus irgendeinem Grund fehlgeschlagen ist
// (z. B. kurzzeitiger Google-Ausfall), UND übernimmt Zeit-Änderungen, die
// direkt in Google an bereits verknüpften Terminen gemacht wurden (Rück-
// richtung, siehe pullGoogleChangesForAllConnectedCalendars). Kein
// Nutzer-Login hier, daher per Secret statt Session abgesichert.
export async function GET(req: NextRequest) {
  const secret = req.nextUrl.searchParams.get("secret");
  if (!process.env.CRON_SECRET || secret !== process.env.CRON_SECRET) {
    return new NextResponse("Unauthorized", { status: 401 });
  }

  const synced = await runGoogleBackfillForAllConnectedCalendars();
  const pulled = await pullGoogleChangesForAllConnectedCalendars();
  return NextResponse.json({
    ok: true,
    calendars: synced.length,
    names: synced.map((c) => c.name),
    pulledUpdates: pulled.updated,
    pulledDeletions: pulled.deleted,
  });
}
