import { NextResponse } from "next/server"; import * as z from "zod/v4"; import { appUrl } from "@/lib/base-path"; 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 { assertImageQuota, generateImage } from "@/lib/ai/image"; import { IMAGE_PROMPT_MAX, IMAGE_SIZES, type ImageSizeKey } from "@/lib/ai/image-shared"; import { putBlob } from "@/lib/storage/blob"; import { logoPalettePrompt } from "@/lib/ai/brand-palette"; import { IMAGE_ART_DIRECTION } from "@/lib/ai/prompts"; export const maxDuration = 360; const ImagePrompt = z.object({ prompt: z.string().describe("The finished English prompt for the image model"), }); const SYSTEM = `You write prompts for an AI image generator. The images illustrate Facebook and Instagram posts for a small Thai business page; a person reads and may edit your prompt before any image is made. - Output one English prompt of 60-140 words: subject, setting, composition, lighting, colour mood, and photographic or illustration style. - Show only what the owner described or what states. Never invent products, packaging, prices or claims. - Ask for no text, lettering, logos, watermarks or brand names inside the image (image models spell Thai badly; the caption carries the words). - No identifiable real people, celebrities or copyrighted characters. If people appear, keep them generic. - No before/after imagery and no exaggerated results (cures, guaranteed outcomes). - Follow "สีและสไตล์ภาพของแบรนด์" exactly when supplied, especially its palette, medium, lighting and exclusions. Match the shop's tone and audience through the visual mood.`; const IMAGE_SYSTEM = `${SYSTEM}\n${IMAGE_ART_DIRECTION}`; /** * Two steps, both explicit button presses in the editor: * - `{ action: "prompt", pageId, description }` → an editable prompt (Codex CLI, nothing saved) * - `{ action: "generate", pageId, prompt, size }` → the image (ChatGPT browser), stored like an upload → `{ url }` * The returned URL only fills the editor; the post still goes through normal approval. */ 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 { // SUPERADMIN passes the role check for any id, so confirm the page exists. const page = await prisma.page.findUnique({ where: { id: pageId }, select: { pictureUrl: true, 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 action = str(body.action); if (action === "prompt") { const description = str(body.description).trim(); if (!description) throw new UserFacingError("บอก AI ว่าอยากได้รูปแบบไหน"); if (description.length > 1000) throw new UserFacingError("คำอธิบายยาวเกิน 1,000 ตัวอักษร"); const logoPalette = await logoPalettePrompt(page.pictureUrl); const result = await generateStructured({ kind: "image-prompt", pageId, userId: auth.user.id, system: IMAGE_SYSTEM, prompt: `${profilePrompt(page.profile)}\n${logoPalette}\n\nWrite the image prompt for the idea below.\n\n\n${description}\n`, schema: ImagePrompt, effort: "low", }); const prompt = result.prompt.trim(); if (!prompt) throw new UserFacingError("AI ตอบกลับไม่ครบ ลองใหม่อีกครั้ง"); return NextResponse.json({ prompt, profileMissing: !page.profile }); } if (action === "generate") { const prompt = str(body.prompt).trim(); const size = str(body.size); if (!prompt) throw new UserFacingError("ใส่คำอธิบายรูปก่อน"); if (prompt.length > IMAGE_PROMPT_MAX) throw new UserFacingError(`คำอธิบายรูปยาวเกิน ${IMAGE_PROMPT_MAX.toLocaleString("th-TH")} ตัวอักษร`); if (!Object.hasOwn(IMAGE_SIZES, size)) throw new UserFacingError("ไม่รู้จักขนาดรูปนี้"); await assertImageQuota(pageId); const image = await generateImage(prompt, size as ImageSizeKey); const file = new File([new Uint8Array(image.bytes)], "ai-image.jpg", { type: image.contentType }); const blob = await putBlob(`posts/${pageId}/ai-image.jpg`, file, { contentType: image.contentType }, appUrl(new URL(req.url).origin)); // Recorded only after the image is stored, so a failed save doesn't spend quota. await prisma.aiUsage.create({ data: { pageId, userId: auth.user.id, kind: "image", inputTokens: image.inputTokens, outputTokens: image.outputTokens }, }); return NextResponse.json({ url: blob.url }); } throw new UserFacingError("ไม่รู้จักคำสั่งนี้"); } catch (e) { return errorResponse(e, "ai:image"); } }