import { NextResponse } from "next/server";
import { randomUUID } from "crypto";
import { requireAuthContext } from "@/lib/auth/authContext";
import { getConvexAuthedHttpClient } from "@/lib/convex/server";
import { api } from "@/lib/convex/api";

export const dynamic = "force-dynamic";

export async function POST(request: Request) {
  const auth = await requireAuthContext();
  const client = await getConvexAuthedHttpClient();

  const { ms }: { ms?: number } = await request.json().catch(() => ({}));
  const id = randomUUID();

  const result = await client.mutation(api.jobs.enqueueDemo, {
    userId: auth.userId,
    id,
    ms,
  });

  return NextResponse.json(result);
}

export async function GET(request: Request) {
  const auth = await requireAuthContext();
  const client = await getConvexAuthedHttpClient();

  const url = new URL(request.url);
  const id = url.searchParams.get("id") ?? "";
  if (!id) {
    return NextResponse.json({ error: "缺少 id" }, { status: 400 });
  }

  const job = await client.query(api.jobs.get, { userId: auth.userId, id });
  if (!job) {
    return NextResponse.json({ error: "任务不存在" }, { status: 404 });
  }

  return NextResponse.json(job);
}
