/**
 * POST /api/competitors/discover-async
 * ─────────────────────────────────────
 * Creates a CompetitorDiscoveryJob for 4+ location discoveries.
 * The cron /api/cron/competitor-discovery-queue processes one location
 * per tick (every minute). Poll GET /api/competitors/jobs/[jobId] for status.
 */

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

export const dynamic = "force-dynamic";

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?: string;
    locations?: string[];
    limit?: number;
  } | null;

  const { brandId, focus, locations, limit } = body ?? {};

  if (!brandId || !focus || !Array.isArray(locations) || locations.length === 0) {
    return NextResponse.json({ error: "brandId, focus, and locations 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 });
  }

  const job = await prisma.competitorDiscoveryJob.create({
    data: {
      brandId,
      status: "pending",
      focus,
      locations,
      limit: limit ?? 20,
      totalLocations: locations.length,
    },
  });

  return NextResponse.json({
    jobId: job.id,
    status: job.status,
    totalLocations: job.totalLocations,
  });
}
