/**
 * GET /api/industry-intel/latest?brandId=X — most recent briefing.
 */

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) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { searchParams } = new URL(req.url);
  const brandId = searchParams.get("brandId");
  const scope = searchParams.get("scope"); // "local" | "national" | null = any
  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 });

  // Scope filter — match the cache key written in generateBriefing()
  // ("local:daily" / "national:daily"). When scope isn't specified
  // we return whatever's most recent regardless of scope (legacy
  // behaviour for callers that haven't been updated yet).
  const where: { brandId: string; period?: string } = { brandId };
  if (scope === "local" || scope === "national") {
    where.period = `${scope}:daily`;
  }

  const briefing = await prisma.industryBriefing.findFirst({
    where,
    orderBy: { generatedAt: "desc" },
  });

  return NextResponse.json({ briefing });
}
