/**
 * GET /api/admin/content
 *
 * Audits + reports overview across the platform. Three rollups in
 * one response (cheaper than three round-trips):
 *
 *   technicalAudits  — last 100 across all brands
 *   performanceAudits — last 100 across all brands
 *   contentBriefs    — last 100 across all brands
 *
 * Each carries the parent brand for context.
 *
 * Superadmin-only.
 */

import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireSuperadmin, withAdminTiming } from "@/lib/admin-auth";

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

const TAKE = 100;

export async function GET() {
  const denied = await requireSuperadmin();
  if (denied) return denied;

  try {
    return NextResponse.json(await withAdminTiming("content.overview", async () => {
    const [technical, performance, briefs, technicalCount, performanceCount, briefsCount] = await Promise.all([
      prisma.technicalAudit.findMany({
        take: TAKE,
        orderBy: { createdAt: "desc" },
        include: { brand: { select: { id: true, name: true, domain: true } } },
      }),
      prisma.performanceAudit.findMany({
        take: TAKE,
        orderBy: { createdAt: "desc" },
        include: { brand: { select: { id: true, name: true, domain: true } } },
      }),
      prisma.contentBrief.findMany({
        take: TAKE,
        orderBy: { createdAt: "desc" },
        include: { brand: { select: { id: true, name: true, domain: true } } },
      }),
      prisma.technicalAudit.count(),
      prisma.performanceAudit.count(),
      prisma.contentBrief.count(),
    ]);

    return {
      counts: {
        technicalAudits: technicalCount,
        performanceAudits: performanceCount,
        contentBriefs: briefsCount,
      },
      technicalAudits: technical.map((a) => ({
        id: a.id,
        crawlHealth: a.crawlHealth,
        status: a.status,
        pagesScanned: a.pagesScanned,
        createdAt: a.createdAt.toISOString(),
        brand: a.brand,
      })),
      performanceAudits: performance.map((a) => ({
        id: a.id,
        status: a.status,
        device: a.device,
        // PerformanceAudit doesn't store an aggregate score itself;
        // page-level scores live on PerformancePageScore. The list
        // surface only needs status + when, so leave score null
        // here and let the brand-detail panel hydrate when needed.
        score: null as number | null,
        createdAt: a.createdAt.toISOString(),
        brand: a.brand,
      })),
      contentBriefs: briefs.map((b) => ({
        id: b.id,
        title: b.title,
        type: b.type,
        primaryKeyword: b.primaryKeyword ?? null,
        status: b.status,
        createdAt: b.createdAt.toISOString(),
        brand: b.brand,
      })),
    };
  }));
  } catch (err) {
    // Structured error response so the client page renders a "Retry"
    // card instead of hanging on a spinner when Prisma times out or
    // the DB connection drops. maxDuration=30 bounds the hang.
    const message = err instanceof Error ? err.message : "unknown error";
    console.error("[admin/content] query failed", { message });
    return NextResponse.json(
      { error: "Audits aggregation failed — try refreshing.", detail: message },
      { status: 500 },
    );
  }
}
