/**
 * GET /api/industry-intel/daily-gsc?brandId=X&days=90
 *
 * Returns daily GSC totals for a brand as a time-series ready to
 * feed into recharts. One row per day with clicks + impressions +
 * position + ctr aggregated across every query/page for that day.
 *
 * Used by the Industry Intel "Performance Correlations" chart, which
 * renders an Actual line (raw clicks) and a Normalized line (7-day
 * trailing moving average) so users can spot divergence tied to the
 * external events the AI briefing flagged.
 *
 * Cheap read — GscPage is already indexed by (brandId, date), groupBy
 * aggregates server-side. Bounded at 365 days to keep the response
 * payload modest for brands with long histories.
 */

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

export const dynamic = "force-dynamic";

const CACHE_HEADERS = {
  // Daily aggregates shift at most once per day (cron-synced) so a
  // 5-min cache is safe. swr=60 lets users see yesterday's numbers
  // while today's sync lands.
  "Cache-Control": "private, max-age=300, stale-while-revalidate=60",
};

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

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

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

  const days = Math.min(365, Math.max(7, parseInt(searchParams.get("days") ?? "90", 10) || 90));
  const since = new Date(Date.now() - days * 86_400_000);

  const rows = await prisma.gscPage.groupBy({
    by: ["date"],
    where: { brandId, date: { gte: since } },
    _sum: { clicks: true, impressions: true },
    // Average-of-averages is rough but matches the way the dashboard
    // summary already reports it — we're charting trend direction,
    // not absolute accuracy for these two fields.
    _avg: { position: true, ctr: true },
    orderBy: { date: "asc" },
  }).catch(() => []);

  const points = rows.map((r) => ({
    date: r.date.toISOString().slice(0, 10),
    clicks: r._sum.clicks ?? 0,
    impressions: r._sum.impressions ?? 0,
    position: r._avg.position != null ? Math.round(r._avg.position * 10) / 10 : null,
    ctr: r._avg.ctr != null ? Math.round(r._avg.ctr * 10000) / 100 : null, // stored 0-1, render as %
  }));

  console.info(`[industry-intel:daily-gsc] ${points.length} daily points (${days}d) brandId=${brandId}`);

  return NextResponse.json({ points, days }, { headers: CACHE_HEADERS });
}
