import { NextRequest, NextResponse } from "next/server";
import { createVideoJob } from "@/lib/jobs/create-job";
import { prisma } from "@/lib/db";
import { requireAuth } from "@/lib/session";
import type { CreateJobPayload } from "@/lib/types";

export const maxDuration = 120;

export async function POST(req: NextRequest) {
  const { error, user } = await requireAuth();
  if (error || !user) return error!;

  const body = (await req.json()) as CreateJobPayload;

  try {
    const job = await createVideoJob(user, body);
    return NextResponse.json({ jobId: job.id });
  } catch (err) {
    const message = err instanceof Error ? err.message : "Failed to create job";
    const status = message.includes("Quota exceeded") ? 403 : 400;
    return NextResponse.json({ error: message }, { status });
  }
}

export async function GET(req: NextRequest) {
  const { error, user } = await requireAuth();
  if (error || !user) return error!;

  const limit = Math.min(Number(req.nextUrl.searchParams.get("limit")) || 20, 100);

  const jobs = await prisma.job.findMany({
    where: { userId: user.id },
    orderBy: { createdAt: "desc" },
    take: limit,
    include: {
      items: {
        select: {
          id: true,
          audioFilename: true,
          title: true,
          status: true,
          youtubeVideoId: true,
          error: true,
        },
      },
    },
  });

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