/**
 * GET /api/content-audit/latest?brandId=X — Get latest content audit.
 * Enriches each page in the results JSON with a "discovered" date
 * derived from the EARLIEST signal we have for that URL across:
 *   1. GscPage (earliest date the URL appeared in Google Search Console)
 *   2. PageRecord (earliest crawl/sitemap detection — path-keyed)
 *   3. TrackedEvent page_view (earliest Site Tag page view)
 *
 * Uses the lowest of all three so the column reflects when meSEO
 * truly first knew the page existed. URLs in the audit are full URLs
 * (https://...) — GscPage matches by pageUrl directly, PageRecord
 * + TrackedEvent need the path stripped from the host first.
 */
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

function urlToPath(url: string): string {
  try { return new URL(url).pathname; } catch { return url; }
}

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

  const brandId = new URL(req.url).searchParams.get("brandId");
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  const audit = await prisma.contentAuditResult.findFirst({
    where: { brandId },
    orderBy: { createdAt: "desc" },
  });

  if (!audit) return NextResponse.json({ audit: null });

  const results = (audit.results ?? []) as Array<Record<string, unknown>>;
  const urls = results.map((r) => String(r.url ?? "")).filter(Boolean);

  if (urls.length > 0) {
    const paths = [...new Set(urls.map(urlToPath))];
    // Get TrackedSite once for the brand (TrackedEvent is keyed by it)
    const trackedSite = await prisma.trackedSite.findUnique({
      where: { brandId }, select: { id: true },
    }).catch(() => null);

    // Batch query all three sources in parallel using GROUP BY for efficiency
    type PrRow = { url: string; firstSeenAt: Date };
    type EvRow = { pageUrl: string; first_seen: Date };

    const [gscGroupRows, prRows, evRows] = await Promise.all([
      // Earliest GSC date per URL (full URL match)
      prisma.gscPage.groupBy({
        by: ["pageUrl"],
        where: { brandId, pageUrl: { in: urls } },
        _min: { date: true },
      }).catch(() => [] as Array<{ pageUrl: string; _min: { date: Date | null } }>),

      // PageRecord — keyed by path
      prisma.pageRecord.findMany({
        where: { brandId, url: { in: paths } },
        select: { url: true, firstSeenAt: true },
      }).catch(() => [] as PrRow[]),

      // TrackedEvent earliest page_view per pageUrl (path-keyed)
      trackedSite ? prisma.$queryRaw<EvRow[]>`
        SELECT "pageUrl", MIN("timestamp") as first_seen
        FROM "TrackedEvent"
        WHERE "trackedSiteId" = ${trackedSite.id}
          AND "eventType" = 'page_view'
          AND "pageUrl" = ANY(${paths}::text[])
        GROUP BY "pageUrl"
      `.catch(() => [] as EvRow[]) : Promise.resolve([] as EvRow[]),
    ]);

    const gscMap = new Map<string, Date>();
    for (const r of gscGroupRows) {
      if (r._min.date) gscMap.set(r.pageUrl, r._min.date);
    }

    const prMap = new Map<string, Date>();
    for (const r of prRows) prMap.set(r.url, r.firstSeenAt);

    const evMap = new Map<string, Date>();
    for (const r of evRows) evMap.set(r.pageUrl, new Date(r.first_seen));

    for (const r of results) {
      const fullUrl = String(r.url ?? "");
      const path = urlToPath(fullUrl);
      const candidates: Array<{ date: Date; source: string }> = [];
      const gsc = gscMap.get(fullUrl);
      if (gsc) candidates.push({ date: gsc, source: "gsc" });
      const pr = prMap.get(path);
      if (pr) candidates.push({ date: pr, source: "sitemap" });
      const ev = evMap.get(path);
      if (ev) candidates.push({ date: ev, source: "site_tag" });

      if (candidates.length > 0) {
        candidates.sort((a, b) => a.date.getTime() - b.date.getTime());
        r.firstSeenAt = candidates[0].date.toISOString();
        r.discoveredSource = candidates[0].source;
      }
    }
  }

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