/**
 * GET /api/dashboard/summary?brandId=…&range=28d
 *
 * Fast endpoint: reads from DashboardSnapshot (precomputed by cron).
 * Returns instantly (<50ms) with the last-computed payload. The
 * dashboard page loads this FIRST for instant paint, then fires the
 * full /api/dashboard in the background for a fresh refresh.
 *
 * If no snapshot exists yet, returns { cached: false } so the page
 * knows to fall through to the live endpoint immediately.
 */

import { NextResponse } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/prisma";
import { validateQuery } from "@/lib/validation/request";
import { BrandIdSchema } from "@/lib/validation/common-schemas";
import { withErrorHandler } from "@/lib/api/with-error-handler";
import { requireUserAndBrand } from "@/lib/auth/require";

export const dynamic = "force-dynamic";

const QuerySchema = z.object({
  brandId: BrandIdSchema.optional(),
  range: z.string().default("28d"),
});

export const GET = withErrorHandler(async (req: Request) => {
  const { brandId, range } = validateQuery(req, QuerySchema);

  if (!brandId) return NextResponse.json({ cached: false }, { status: 200 });

  await requireUserAndBrand(brandId);

  const snapshot = await prisma.dashboardSnapshot.findUnique({
    where: { brandId_range: { brandId, range } },
    select: { payload: true, computedAt: true },
  }).catch(() => null);

  if (!snapshot) {
    return NextResponse.json({ cached: false });
  }

  const ageMs = Date.now() - snapshot.computedAt.getTime();
  const ageMinutes = Math.round(ageMs / 60_000);

  return NextResponse.json({
    cached: true,
    computedAt: snapshot.computedAt.toISOString(),
    ageMinutes,
    stale: ageMs > 60 * 60 * 1000, // > 1 hour = stale
    ...(snapshot.payload as Record<string, unknown>),
  });
});
