import { NextRequest, NextResponse } from "next/server";
import { Receiver } from "@upstash/qstash";
import { prisma } from "@/lib/db";
import { getBuffer } from "@/lib/storage";
import { processFile } from "@/lib/ocr";

const receiver = new Receiver({
  currentSigningKey: process.env.QSTASH_CURRENT_SIGNING_KEY!,
  nextSigningKey: process.env.QSTASH_NEXT_SIGNING_KEY!,
});

export async function POST(request: NextRequest) {
  try {
    const body = await request.text();

    const isValid = await receiver.verify({
      signature: request.headers.get("upstash-signature") || "",
      body,
    });

    if (!isValid) {
      return NextResponse.json({ error: "Invalid signature" }, { status: 401 });
    }

    const { jobId } = JSON.parse(body) as { jobId: string };

    const job = await prisma.processingJob.findUnique({ where: { id: jobId } });
    if (!job) {
      return NextResponse.json({ error: "Job not found" }, { status: 404 });
    }

    if (job.status !== "queued") {
      return NextResponse.json({ ok: true, skipped: true, reason: `Job status is ${job.status}` });
    }

    const sourceKey = `sources/${job.id}/${job.fileName}`;
    const fileBuffer = await getBuffer(sourceKey);
    const isPdf = job.fileName.toLowerCase().endsWith(".pdf");

    const cardIds = await processFile(job.id, job.fileName, fileBuffer, isPdf);

    return NextResponse.json({ ok: true, cardIds });
  } catch (error) {
    console.error("[jobs/process POST]", error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Processing failed" },
      { status: 500 }
    );
  }
}
