import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { recoverStuckJobs } from "@/lib/job-recovery";
import { requireApiAuthWithOrg, handleApiError } from "@/lib/api-auth";

export async function GET(request: NextRequest) {
  recoverStuckJobs().catch(() => {});

  try {
    const session = await requireApiAuthWithOrg();
    const orgId = session.user.orgId;
    const userId = request.nextUrl.searchParams.get("userId") || undefined;
    const effectiveUserId = userId === "me" ? session.user.id : userId;

    const [total, byOcrStatus, byReviewStatus, myCards] = await Promise.all([
      prisma.responseCard.count({ where: { organizationId: orgId } }),
      prisma.responseCard.groupBy({
        by: ["ocrStatus"],
        where: { organizationId: orgId },
        _count: { id: true },
      }),
      prisma.responseCard.groupBy({
        by: ["reviewStatus"],
        where: { organizationId: orgId },
        _count: { id: true },
      }),
      effectiveUserId
        ? prisma.responseCard.count({
            where: { assignedToId: effectiveUserId, organizationId: orgId },
          })
        : prisma.responseCard.count({
            where: { assignedToId: session.user.id, organizationId: orgId },
          }),
    ]);

    const ocrStatusCounts = Object.fromEntries(
      byOcrStatus.map((r) => [r.ocrStatus, r._count.id])
    );
    const reviewStatusCounts = Object.fromEntries(
      byReviewStatus.map((r) => [r.reviewStatus, r._count.id])
    );

    return NextResponse.json({
      total,
      byOcrStatus: ocrStatusCounts,
      byReviewStatus: reviewStatusCounts,
      myCards,
    });
  } catch (error) {
    return handleApiError(error);
  }
}
