import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { uploadBuffer } from "@/lib/storage";
import { enqueueProcessing } from "@/lib/processing-queue";
import { requireApiAuthWithOrg, handleApiError } from "@/lib/api-auth";

const MAX_UPLOAD_SIZE = 50 * 1024 * 1024; // 50 MB

const ALLOWED_TYPES = [
  "application/pdf",
  "image/jpeg",
  "image/jpg",
  "image/png",
  "image/webp",
];

export async function POST(request: NextRequest) {
  try {
    const session = await requireApiAuthWithOrg("uploads.create");
    const formData = await request.formData();
    const files = [
      ...(formData.getAll("files") as File[]),
      ...(formData.get("file") ? [formData.get("file") as File] : []),
    ].filter(Boolean);

    if (!files?.length) {
      return NextResponse.json(
        { error: "No files provided" },
        { status: 400 }
      );
    }

    const jobIds: string[] = [];

    for (const file of files) {
      if (!(file instanceof File)) continue;

      const contentType = file.type;
      if (!ALLOWED_TYPES.includes(contentType)) {
        return NextResponse.json(
          { error: `Invalid file type: ${contentType}. Allowed: PDF, JPEG, PNG, WebP` },
          { status: 400 }
        );
      }

      if (file.size > MAX_UPLOAD_SIZE) {
        return NextResponse.json(
          { error: `File "${file.name}" exceeds the 50 MB limit` },
          { status: 400 }
        );
      }

      const buffer = Buffer.from(await file.arrayBuffer());
      const fileName = file.name || `upload-${Date.now()}`;

      const job = await prisma.processingJob.create({
        data: {
          fileName,
          filePath: `sources/${fileName}`,
          status: "queued",
          organizationId: session.user.orgId,
        },
      });

      const sourceKey = `sources/${job.id}/${fileName}`;
      await uploadBuffer(sourceKey, buffer, contentType);

      await enqueueProcessing(job.id);
      jobIds.push(job.id);
    }

    return NextResponse.json({ jobIds });
  } catch (error) {
    return handleApiError(error);
  }
}
