/**
 * GET /api/competitors/[id]/pages?status=new&limit=50&offset=0
 *
 * Returns CompetitorPage rows for a given competitor, filterable by
 * status (new, updated, removed, unchanged). Supports pagination.
 * Used by the Competitor Intel UI for the Recent Activity feed,
 * Content Gap Analysis, and Head-to-Head comparison views.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

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

  const comp = await prisma.competitor.findUnique({
    where: { id: params.id },
    include: { brand: { include: { organization: { include: { memberships: true } } } } },
  });
  if (!comp) return NextResponse.json({ error: "Not found" }, { status: 404 });
  if (!comp.brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  const { searchParams } = new URL(req.url);
  const status = searchParams.get("status"); // new | updated | removed | unchanged
  const limit = Math.min(parseInt(searchParams.get("limit") ?? "50", 10), 200);
  const offset = parseInt(searchParams.get("offset") ?? "0", 10);

  const where: Record<string, unknown> = { competitorId: params.id };
  if (status) where.status = status;

  const [pages, total] = await Promise.all([
    prisma.competitorPage.findMany({
      where,
      orderBy: { firstSeenAt: "desc" },
      take: limit,
      skip: offset,
      select: {
        id: true, url: true, title: true, metaDescription: true,
        h1: true, wordCount: true, lastmod: true, status: true,
        firstSeenAt: true, lastCheckedAt: true,
      },
    }),
    prisma.competitorPage.count({ where }),
  ]);

  // Also return summary counts for the filter tabs
  const counts = await prisma.competitorPage.groupBy({
    by: ["status"],
    where: { competitorId: params.id },
    _count: true,
  });
  const statusCounts: Record<string, number> = {};
  for (const c of counts) statusCounts[c.status] = c._count;

  // Aggregate word-count metrics across every page we've crawled for
  // this competitor. The CompetitorCard renders these as a "Avg
  // Words" stat so users see the typical content depth at a glance
  // — before this, wordCount lived on each page row but was never
  // surfaced at the competitor level. Excludes "removed" pages so
  // the average reflects the competitor's CURRENT content footprint,
  // not what they've stripped out. _avg ignores null wordCount rows
  // automatically, so partial-crawl competitors still produce a
  // meaningful number.
  const wordStats = await prisma.competitorPage.aggregate({
    where: {
      competitorId: params.id,
      status: { notIn: ["removed"] },
      wordCount: { gt: 0 },
    },
    _avg: { wordCount: true },
    _count: { wordCount: true },
    _max: { wordCount: true },
    _min: { wordCount: true },
  });

  return NextResponse.json({
    pages,
    total,
    limit,
    offset,
    statusCounts,
    wordStats: {
      avg: wordStats._avg.wordCount != null ? Math.round(wordStats._avg.wordCount) : null,
      max: wordStats._max.wordCount,
      min: wordStats._min.wordCount,
      // Number of pages that actually contributed to the average.
      // Surfaced so the client can render "Avg Words (across 18
      // pages)" and distinguish a thin sample from a comprehensive
      // one.
      pagesWithContent: wordStats._count.wordCount,
    },
    sitemapHealth: {
      lastCrawledAt: comp.lastCrawledAt,
      detectedCms: comp.detectedCms,
      sitemapUrls: comp.sitemapUrls,
    },
  });
}
