import { NextResponse } from "next/server"; import * as z from "zod/v4"; import { prisma } from "@/lib/db"; import { requirePageAction } from "@/lib/auth/user"; import { errorResponse, readJson, str } from "@/lib/http"; import { UserFacingError } from "@/lib/facebook/client"; import { generateStructured } from "@/lib/ai/claude"; import { CAPTION_REFINEMENTS, profilePrompt, type CaptionRefinement } from "@/lib/ai/shared"; import { CAPTION_RULES, platformRule } from "@/lib/ai/prompts"; export const maxDuration = 300; const CaptionVariants = z.object({ variants: z.array( z.object({ angle: z.string().describe("2-4 Thai words naming the approach, e.g. เน้นโปร, เล่าเรื่อง, ชวนคอมเมนต์"), caption: z.string().describe("The full caption, ready to post"), }) ), }); const SYSTEM = `You write Facebook and Instagram captions for a small Thai business page. The owner picks one of your variants, may edit it, and it still goes through human approval before posting. ${CAPTION_RULES}`; /** * `{ pageId, targets, topic }` → 3 new captions, or `{ pageId, targets, caption, refine }` → 2 rewrites. * Nothing is saved: the editor puts the chosen text into the draft. */ 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 instagram = Array.isArray(body.targets) && body.targets.includes("INSTAGRAM"); const topic = str(body.topic).trim(); const caption = str(body.caption).trim(); const refine = str(body.refine); const refinement = Object.hasOwn(CAPTION_REFINEMENTS, refine) ? CAPTION_REFINEMENTS[refine as CaptionRefinement] : null; if (refine && !refinement) throw new UserFacingError("ไม่รู้จักรูปแบบการปรับนี้"); if (refinement && !caption) throw new UserFacingError("เขียน caption ก่อน แล้วค่อยให้ AI ปรับ"); if (!refinement && !topic) throw new UserFacingError("บอก AI ว่าอยากโพสต์เรื่องอะไร"); if (topic.length > 1000) throw new UserFacingError("หัวข้อยาวเกิน 1,000 ตัวอักษร"); if (caption.length > 5000) throw new UserFacingError("caption ยาวเกินกว่าที่ AI จะปรับให้ได้ (5,000 ตัวอักษร)"); // SUPERADMIN passes the role check for any id, so confirm the page exists. const page = await prisma.page.findUnique({ where: { id: pageId }, select: { profile: { select: { business: true, audience: true, tone: true, visualStyle: true, avoid: true, cta: true, website: true } } }, }); if (!page) return NextResponse.json({ error: "ไม่พบเพจ" }, { status: 404 }); const profile = page.profile; const task = refinement ? `Rewrite the caption below: ${refinement.instruction}. Keep its facts and any [placeholders]. Return 2 variants.\n\n