import { NextRequest, NextResponse } from "next/server";
import { requireApiUser } from "@/lib/api-auth";
import { prisma } from "@/lib/db";

export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  const { error, user } = await requireApiUser(_req);
  if (error || !user) return error!;

  const { id } = await params;

  const job = await prisma.job.findFirst({
    where: { id, userId: user.id },
    include: {
      items: {
        orderBy: { audioFilename: "asc" },
        select: {
          id: true,
          audioFilename: true,
          title: true,
          description: true,
          tags: true,
          privacy: true,
          categoryId: true,
          resolution: true,
          status: true,
          youtubeVideoId: true,
          error: true,
        },
      },
    },
  });

  if (!job) {
    return NextResponse.json({ error: "Job not found" }, { status: 404 });
  }

  return NextResponse.json({
    id: job.id,
    status: job.status,
    createdAt: job.createdAt.toISOString(),
    completedAt: job.completedAt?.toISOString() ?? null,
    items: job.items,
  });
}
