import { NextResponse } from "next/server"; import * as z from "zod/v4"; import { prisma } from "@/lib/db"; import { actorLabel, requirePageAction } from "@/lib/auth/user"; import { audit } from "@/lib/audit"; import { readJson, str, errorResponse } from "@/lib/http"; import { UserFacingError } from "@/lib/facebook/client"; import { JOB_SELECT } from "@/lib/ai/post-queue"; import { IMAGE_DAILY_LIMIT_PER_PAGE } from "@/lib/ai/image"; import { bkkMidnight, isDayKey } from "@/lib/board"; const Input = z.object({ requestKey: z.uuid(), topic: z.string().trim().min(1).max(1000), targets: z.array(z.enum(["FACEBOOK", "INSTAGRAM"])).min(1).max(2), plannedDay: z.string().optional() }); export async function GET(req: Request) { const pageId = new URL(req.url).searchParams.get("pageId") || ""; const auth = await requirePageAction(pageId, "editPost"); if (!auth.ok) return auth.response; const jobs = await prisma.postGenerationJob.findMany({ where: { pageId }, select: JOB_SELECT, orderBy: [{ createdAt: "desc" }, { id: "desc" }], take: 30 }); return NextResponse.json({ jobs }, { headers: { "Cache-Control": "no-store" } }); } export async function POST(req: Request) { const body = await readJson(req); const pageId = str(body.pageId); const auth = await requirePageAction(pageId, "editPost"); if (!auth.ok) return auth.response; try { const input = Input.safeParse(body); if (!input.success) throw new UserFacingError("กรอกหัวข้อไม่เกิน 1,000 ตัวอักษร และเลือกช่องทางก่อนเข้าคิว"); const { requestKey, topic, plannedDay } = input.data; const targets = [...new Set(input.data.targets)].sort(); if (plannedDay && !isDayKey(plannedDay)) throw new UserFacingError("วันที่วางแผนโพสต์ไม่ถูกต้อง"); const plannedAt = plannedDay ? bkkMidnight(plannedDay) : null; const result = await prisma.$transaction(async (tx) => { await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`ai-post:${pageId}`}))`; const existing = await tx.postGenerationJob.findUnique({ where: { requestedById_requestKey: { requestedById: auth.user.id, requestKey } } }); if (existing) { if (existing.pageId !== pageId || existing.topic !== topic || existing.targets.join() !== targets.join() || existing.plannedAt?.toISOString() !== plannedAt?.toISOString()) throw new UserFacingError("คำขอนี้ใช้กับงานอื่นแล้ว กรุณาสร้างคำขอใหม่"); return { job: existing, duplicate: true }; } const page = await tx.page.findUnique({ where: { id: pageId }, select: { status: true, igUserId: true, profile: { select: { business: true, audience: true, tone: true, visualStyle: true, avoid: true, cta: true, website: true } } } }); if (!page || page.status === "DISCONNECTED") throw new UserFacingError("ไม่พบเพจที่พร้อมสร้างโพสต์"); if (!page.profile?.business.trim()) throw new UserFacingError("ตั้งค่าโปรไฟล์ร้านก่อน เพื่อให้ AI สร้างโพสต์จากข้อมูลจริงของร้าน"); if (targets.includes("INSTAGRAM") && !page.igUserId) throw new UserFacingError("เพจนี้ยังไม่ได้ผูก Instagram"); const pending = await tx.postGenerationJob.count({ where: { pageId, status: { in: ["QUEUED", "RUNNING"] } } }); if (pending >= 5) throw new UserFacingError("เพจนี้มีงานค้างครบ 5 งานแล้ว รอให้เสร็จก่อนเพิ่มคิว"); const used = await tx.aiUsage.count({ where: { pageId, kind: "image", createdAt: { gte: new Date(Date.now() - 24 * 60 * 60_000) } } }); if (used + pending >= IMAGE_DAILY_LIMIT_PER_PAGE) throw new UserFacingError("โควตาภาพของเพจนี้ถูกใช้หรือจองเต็มแล้ว ลองใหม่ภายหลัง"); const job = await tx.postGenerationJob.create({ data: { pageId, requestedById: auth.user.id, requestKey, topic, targets, plannedAt, profileSnapshot: page.profile } }); await audit({ action: "AI_POST_QUEUED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), pageId, detail: { jobId: job.id } }, tx); return { job, duplicate: false }; }); const job = await prisma.postGenerationJob.findUniqueOrThrow({ where: { id: result.job.id }, select: JOB_SELECT }); return NextResponse.json({ job, duplicate: result.duplicate }, { status: result.duplicate ? 200 : 202 }); } catch (error) { return errorResponse(error, "post-queue:create"); } }