/**
 * GET /api/cron/backlink-sync — weekly backlink monitoring.
 */
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { syncBacklinks } from "@/lib/services/backlink-monitor";

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

const CRON_SECRET = process.env.CRON_SECRET ?? "";

function authOk(req: Request): boolean {
  if (!CRON_SECRET) return false;
  const header = req.headers.get("authorization") ?? "";
  if (header === `Bearer ${CRON_SECRET}`) return true;
  return new URL(req.url).searchParams.get("secret") === CRON_SECRET;
}

export async function GET(req: Request) {
  if (!authOk(req)) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  // Find brands with GSC connected
  const brands = await prisma.brandIntegration.findMany({
    where: { integrationId: "gsc", connected: true },
    select: { brandId: true, brand: { select: { domain: true } } },
    take: 50,
  });

  const results: Array<{ domain: string; total: number; newCount: number; lostCount: number }> = [];

  for (const bi of brands) {
    try {
      const r = await syncBacklinks(bi.brandId);
      results.push({ domain: bi.brand.domain, ...r });

      // Signals
      if (r.newCount >= 5) {
        await prisma.siteEvent.create({ data: { brandId: bi.brandId, pageUrl: bi.brand.domain, eventType: "backlinks_momentum", eventData: { title: `${r.newCount} new backlinks acquired this week`, count: r.newCount } as object } }).catch(() => {});
      }
      const newToxic = await prisma.backlink.count({ where: { brandId: bi.brandId, toxicityScore: { gte: 60 }, firstSeenAt: { gte: new Date(Date.now() - 7 * 86400000) } } });
      if (newToxic > 0) {
        await prisma.siteEvent.create({ data: { brandId: bi.brandId, pageUrl: bi.brand.domain, eventType: "backlinks_toxic", eventData: { title: `${newToxic} new toxic backlinks detected`, count: newToxic } as object } }).catch(() => {});
      }
      const highDaNew = await prisma.backlink.findFirst({ where: { brandId: bi.brandId, status: "new", domainAuthority: { gte: 50 }, firstSeenAt: { gte: new Date(Date.now() - 7 * 86400000) } }, select: { sourceDomain: true, domainAuthority: true } });
      if (highDaNew) {
        await prisma.siteEvent.create({ data: { brandId: bi.brandId, pageUrl: bi.brand.domain, eventType: "backlink_high_authority", eventData: { title: `New backlink from ${highDaNew.sourceDomain} (DA ${highDaNew.domainAuthority})`, domain: highDaNew.sourceDomain } as object } }).catch(() => {});
      }
    } catch (err) { console.error(`[cron/backlinks] ${bi.brand.domain}`, err); }
  }

  return NextResponse.json({ synced: results.length, results });
}
