/**
 * GET /api/client-portal/dashboard?brandId=X
 * Client-facing dashboard KPIs. Auth'd via client session.
 */

import { NextResponse } from "next/server";
import { requireClientAuth, pageAllowed } from "@/lib/client-auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

export async function GET(req: Request) {
  const brandId = new URL(req.url).searchParams.get("brandId") || "";
  const auth = await requireClientAuth(brandId);
  if (!auth.ok) return NextResponse.json({ error: auth.error }, { status: auth.status });
  if (!pageAllowed(auth.session, "dashboard")) return NextResponse.json({ error: "Page not allowed" }, { status: 403 });

  const now = new Date();
  const since = new Date(now.getTime() - 28 * 86400000);

  const [gscAgg, latestSnapshot, audit, rankKeywords] = await Promise.all([
    prisma.gscPage.aggregate({ where: { brandId, date: { gte: since } }, _sum: { clicks: true, impressions: true }, _avg: { ctr: true, position: true } }),
    prisma.metricSnapshot.findFirst({ where: { brandId, source: "ga4", date: { gte: since } }, orderBy: { date: "desc" } }),
    prisma.technicalAudit.findFirst({ where: { brandId }, orderBy: { createdAt: "desc" }, select: { crawlHealth: true } }),
    prisma.trackedKeyword.count({ where: { brandId, isActive: true } }),
  ]);

  return NextResponse.json({
    brandId,
    period: "28d",
    gsc: {
      clicks: gscAgg._sum.clicks || 0,
      impressions: gscAgg._sum.impressions || 0,
      ctr: Math.round((gscAgg._avg.ctr || 0) * 10000) / 100,
      avgPosition: Math.round((gscAgg._avg.position || 0) * 10) / 10,
    },
    ga4: latestSnapshot ? {
      sessions: latestSnapshot.sessions,
      conversions: latestSnapshot.conversions,
      users: latestSnapshot.users,
    } : null,
    health: audit?.crawlHealth ?? null,
    trackedKeywords: rankKeywords,
    portal: {
      agencyName: auth.session.agencyName,
      agencyLogo: auth.session.agencyLogo,
      primaryColor: auth.session.primaryColor,
      portalConfig: auth.session.portalConfig ?? null,
    },
  });
}
