/**
 * GET /api/cron/nango-sync
 *
 * Daily cron that syncs data from all Nango-managed integrations
 * into meSEO's database. Each brand's connectionId = brandId.
 * Schedule: "0 6 * * *" (6 AM UTC daily)
 */

import { NextResponse } from "next/server";
import { listNangoConnections, isNangoConfigured } from "@/lib/integrations/nango";
import { logCron } from "@/lib/services/cron-logger";

export const dynamic = "force-dynamic";
export const maxDuration = 120;

export async function GET(req: Request) {
  const cronSecret = process.env.CRON_SECRET;
  if (!cronSecret) {
    return NextResponse.json({ error: "Server misconfigured: CRON_SECRET unset" }, { status: 500 });
  }
  const authHeader = req.headers.get("authorization");
  const querySecret = new URL(req.url).searchParams.get("secret");
  if (authHeader !== `Bearer ${cronSecret}` && querySecret !== cronSecret) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  if (!isNangoConfigured()) {
    return NextResponse.json({ configured: false, synced: 0 });
  }

  return logCron("/api/cron/nango-sync", async () => {
    const connections = await listNangoConnections();

    const results: Array<{
      brandId: string;
      provider: string;
      status: "success" | "skipped" | "error";
      message?: string;
    }> = [];

    for (const conn of connections) {
      const brandId = conn.connection_id;
      const provider = conn.provider_config_key;

      try {
        // For now, log the connection — actual per-provider sync
        // handlers will be added as each integration is configured
        // in Nango's dashboard (Google Ads, CallRail, HubSpot, etc.)
        results.push({
          brandId,
          provider,
          status: "skipped",
          message: "Sync handler not yet configured for this provider",
        });
      } catch (err) {
        results.push({
          brandId,
          provider,
          status: "error",
          message: err instanceof Error ? err.message : String(err),
        });
      }
    }

    const payload = {
      connections: connections.length,
      synced: results.filter((r) => r.status === "success").length,
      skipped: results.filter((r) => r.status === "skipped").length,
      errors: results.filter((r) => r.status === "error").length,
      results,
    };
    return NextResponse.json(payload);
  });
}
