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

const DELAY_BETWEEN_CARDS_MS = 3_000;

export async function POST(request: NextRequest) {
  try {
    const session = await requireApiAuthWithOrg("cards.reprocess");
    const body = await request.json().catch(() => ({}));
    const ids = body.ids as string[] | undefined;

    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return NextResponse.json({ error: "No card IDs provided" }, { status: 400 });
    }

    const cards = await prisma.responseCard.findMany({
      where: { id: { in: ids }, organizationId: session.user.orgId },
      select: { id: true, ocrStatus: true, backImagePath: true, frontImagePath: true },
    });

    const eligible = cards.filter(
      (c) => c.ocrStatus !== "processing" && (c.backImagePath || c.frontImagePath)
    );

    if (eligible.length === 0) {
      return NextResponse.json(
        { error: "No eligible cards (already processing or no images)" },
        { status: 400 }
      );
    }

    await prisma.responseCard.updateMany({
      where: { id: { in: eligible.map((c) => c.id) }, organizationId: session.user.orgId },
      data: { ocrStatus: "processing", ocrError: null },
    });

    (async () => {
      for (let i = 0; i < eligible.length; i++) {
        try {
          await reprocessCard(eligible[i].id);
        } catch (err) {
          console.error(`[reprocess-batch] Card ${eligible[i].id} failed:`, err);
        }
        if (i < eligible.length - 1) {
          await new Promise((r) => setTimeout(r, DELAY_BETWEEN_CARDS_MS));
        }
      }
      console.log(`[reprocess-batch] Completed ${eligible.length} card(s)`);
    })().catch((err) => {
      console.error("[reprocess-batch] Background task failed:", err);
    });

    return NextResponse.json({
      ok: true,
      queued: eligible.length,
      skipped: ids.length - eligible.length,
    });
  } catch (error) {
    return handleApiError(error);
  }
}
