/**
 * POST /api/competitors/discover  Body: { brandId, focus?, limit?, locations? }
 * ──────────────────────────────────────────────────────────────────────────────
 * AI + DataForSEO competitor discovery. See
 * src/lib/services/competitor-discovery.ts for the two-stage pipeline.
 *
 * Returns the deduped + validated candidate list. Adding a candidate
 * happens via the existing POST /api/competitors/add (one call per
 * checked candidate, fired client-side after the user picks).
 *
 * When locations[] is supplied (max 3), a separate AI pass runs per
 * location and results are merged. Each candidate carries
 * discoveredForLocations[] so the UI can show where it was found.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { discoverCompetitors } from "@/lib/services/competitor-discovery";
import { trackEvent } from "@/lib/services/platform-telemetry";

export const dynamic = "force-dynamic";
export const maxDuration = 180;

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

  const body = (await req.json().catch(() => null)) as {
    brandId?: string;
    focus?: "local" | "national";
    limit?: number;
    locations?: string[];
  } | null;

  if (!body?.brandId) {
    return NextResponse.json({ error: "brandId required" }, { status: 400 });
  }

  if (body.locations !== undefined) {
    if (!Array.isArray(body.locations)) {
      return NextResponse.json({ error: "locations must be an array" }, { status: 400 });
    }
    if (body.locations.length > 3) {
      return NextResponse.json({
        error: "Maximum 3 locations per run. Background queue coming soon for larger discoveries.",
      }, { status: 400 });
    }
  }

  const brand = await prisma.brand.findUnique({
    where: { id: body.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 });
  }

  try {
    const result = await discoverCompetitors(body.brandId, {
      focus: body.focus ?? "local",
      limit: body.limit ?? 8,
      locations: body.locations,
    });
    trackEvent({
      userId: user.id,
      brandId: body.brandId,
      action: "discover_competitors",
      category: "seo",
      metadata: {
        focus: body.focus ?? "local",
        limit: body.limit ?? 8,
        locationsCount: result.locationsRun.length,
      },
      request: req,
    });
    return NextResponse.json({
      ...result,
      multiLocation: result.locationsRun.length > 1,
    });
  } catch (err) {
    const msg = err instanceof Error ? err.message : "Discovery failed";
    console.error("[/api/competitors/discover]", msg);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
