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 { profilePrompt } from "@/lib/ai/shared"; import { CAPTION_RULES, platformRule } from "@/lib/ai/prompts"; import { addDays, bkkDayKey, bkkMidnight, isDayKey, weekStartOf } from "@/lib/board"; export const maxDuration = 300; const WeekPlan = z.object({ posts: z.array( z.object({ day: z.string().describe("One of the open dates, exactly as given (YYYY-MM-DD)"), title: z.string().describe("Short internal title in Thai"), pillar: z.string().describe("Content type in Thai: ขายของ, ให้ความรู้, รีวิว/ความมั่นใจ, ชวนคุย or เบื้องหลัง"), caption: z.string().describe("The full caption, ready to post"), }) ), }); const SYSTEM = `You plan a week of Facebook posts for a small Thai business and write each caption. The owner ticks the ideas they want; each becomes a draft that still needs human approval before posting. - Mix content types across the week instead of selling every day: offers, useful tips, reviews or trust, questions that invite comments, behind the scenes. - Spread the posts over the open dates and don't repeat what is already planned. - Don't tie a post to a holiday or event unless the owner's goal mentions it. ${CAPTION_RULES}`; const weekday = new Intl.DateTimeFormat("en-US", { weekday: "long", timeZone: "Asia/Bangkok" }); /** `{ pageId, week, goal, count }` → proposed posts for the open days of that week. Nothing is saved. */ 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 week = str(body.week); if (!isDayKey(week) || weekStartOf(week) !== week) throw new UserFacingError("สัปดาห์ไม่ถูกต้อง"); const count = Number(body.count); if (!Number.isInteger(count) || count < 1 || count > 7) throw new UserFacingError("จำนวนโพสต์ต้องอยู่ระหว่าง 1–7"); const goal = str(body.goal).trim(); if (goal.length > 500) throw new UserFacingError("เป้าหมายยาวเกิน 500 ตัวอักษร"); const today = bkkDayKey(new Date()); const open = Array.from({ length: 7 }, (_, i) => addDays(week, i)).filter((d) => d >= today); if (open.length === 0) throw new UserFacingError("สัปดาห์นี้ผ่านไปแล้ว เลือกสัปดาห์ถัดไป"); 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 from = bkkMidnight(week); const to = bkkMidnight(addDays(week, 7)); const planned = await prisma.post.findMany({ where: { pageId, OR: [{ scheduledPublishAt: { gte: from, lt: to } }, { scheduledPublishAt: null, plannedAt: { gte: from, lt: to } }] }, select: { title: true, plannedAt: true, scheduledPublishAt: true }, }); const plannedLines = planned.map((p) => `${bkkDayKey((p.scheduledPublishAt ?? p.plannedAt)!)}: ${p.title}`); const prompt = [ profilePrompt(page.profile), platformRule(false), `Open dates: ${open.map((d) => `${d} (${weekday.format(bkkMidnight(d))})`).join(", ")}`, `Already planned this week:\n${plannedLines.join("\n") || "(nothing yet)"}`, `\n${goal || "(no goal given — plan a balanced week)"}\n`, `Plan exactly ${count} posts.`, ].join("\n\n"); const result = await generateStructured({ kind: "week-plan", pageId, userId: auth.user.id, system: SYSTEM, prompt, schema: WeekPlan, effort: "low" }); const posts = result.posts .map((p) => ({ day: p.day.trim(), title: p.title.trim().slice(0, 120), pillar: p.pillar.trim().slice(0, 40), caption: p.caption.trim() })) .filter((p) => open.includes(p.day) && p.title && p.caption) .slice(0, count) .sort((a, b) => a.day.localeCompare(b.day)); if (posts.length === 0) throw new UserFacingError("AI ตอบกลับไม่ครบ ลองใหม่อีกครั้ง"); return NextResponse.json({ posts, profileMissing: !page.profile }); } catch (e) { return errorResponse(e, "ai:week-plan"); } }