/**
 * GET /api/competitors/jobs/[jobId]
 * ──────────────────────────────────
 * Poll a CompetitorDiscoveryJob for status + progress.
 * Returns status, processedLocations/totalLocations, competitorsFound.
 */

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

  const job = await prisma.competitorDiscoveryJob.findUnique({
    where: { id: params.jobId },
    include: {
      brand: { include: { organization: { include: { memberships: true } } } },
    },
  });

  if (!job) return NextResponse.json({ error: "Job not found" }, { status: 404 });
  if (!job.brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  return NextResponse.json({
    id: job.id,
    status: job.status,
    focus: job.focus,
    totalLocations: job.totalLocations,
    processedLocations: job.processedLocations,
    competitorsFound: job.competitorsFound,
    startedAt: job.startedAt,
    completedAt: job.completedAt,
    error: job.error,
  });
}
