import { NextResponse } from "next/server"; import { prisma } from "@/lib/db"; import { actorLabel, requirePageAction } from "@/lib/auth/user"; import { audit } from "@/lib/audit"; import { JOB_SELECT } from "@/lib/ai/post-queue"; export async function GET(_req: Request, ctx: RouteContext<"/api/ai/post-jobs/[id]">) { const { id } = await ctx.params; const job = await prisma.postGenerationJob.findUnique({ where: { id }, select: { pageId: true } }); if (!job) return NextResponse.json({ error: "ไม่พบงาน" }, { status: 404 }); const auth = await requirePageAction(job.pageId, "editPost"); if (!auth.ok) return auth.response; return NextResponse.json({ job: await prisma.postGenerationJob.findUnique({ where: { id }, select: JOB_SELECT }) }, { headers: { "Cache-Control": "no-store" } }); } export async function DELETE(_req: Request, ctx: RouteContext<"/api/ai/post-jobs/[id]">) { const { id } = await ctx.params; const job = await prisma.postGenerationJob.findUnique({ where: { id }, select: { pageId: true } }); if (!job) return NextResponse.json({ error: "ไม่พบงาน" }, { status: 404 }); const auth = await requirePageAction(job.pageId, "editPost"); if (!auth.ok) return auth.response; const cancelled = await prisma.$transaction(async (tx) => { const changed = await tx.postGenerationJob.updateMany({ where: { id, status: "QUEUED" }, data: { status: "CANCELLED", stage: "cancelled", finishedAt: new Date() } }); if (!changed.count) return false; await audit({ action: "AI_POST_CANCELLED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), pageId: job.pageId, detail: { jobId: id } }, tx); return true; }); if (!cancelled) return NextResponse.json({ error: "ยกเลิกได้เฉพาะงานที่ยังรอคิว งานนี้เริ่มทำหรือจบแล้ว" }, { status: 409 }); return NextResponse.json({ ok: true }); }