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

/**
 * GET /api/signals?brandId=xxx
 * Returns generated signals from all platform data.
 */
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");
  // Return an empty array (not an error) when brandId is absent —
  // the /signals page sometimes calls before brand context resolves,
  // and a 400 bubbles up as "HTTP 400" in the user's banner. 200 with
  // an empty array lets the page show the empty state cleanly and
  // auto-refresh once brand.id is populated.
  if (!brandId || brandId.length < 5) {
    return NextResponse.json([], { status: 200 });
  }

  // Membership check — wrap in try/catch so a DB timeout here doesn't
  // escape as an unhandled rejection (Next.js would surface it as a 500).
  // Graceful: return empty array rather than error so the page renders.
  let brand: { organization: { memberships: { userId: string }[] } } | null = null;
  try {
    brand = await prisma.brand.findUnique({
      where: { id: brandId },
      select: {
        id: true,
        organization: { select: { memberships: { select: { userId: true } } } },
      },
    });
  } catch (err) {
    console.error("[signals] brand lookup failed", { brandId, error: err instanceof Error ? err.message : String(err) });
    return NextResponse.json([], { status: 200 });
  }
  if (!brand || !brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  try {
    const signals = await generateSignals(brandId);
    return NextResponse.json(signals);
  } catch (err) {
    console.error("[signals] ERROR:", err instanceof Error ? err.message : String(err));
    return NextResponse.json({ error: "Failed to generate signals", signals: [] }, { status: 200 });
  }
}
