import { NextResponse } from "next/server"; import { prisma } from "@/lib/db"; import { requirePageAction } from "@/lib/auth/user"; import { audit } from "@/lib/audit"; import { errorResponse, readJson, str } from "@/lib/http"; type Ctx = { params: Promise<{ pageId: string }> }; export async function GET(_req: Request, ctx: Ctx) { const { pageId } = await ctx.params; const auth = await requirePageAction(pageId, "view"); if (!auth.ok) return auth.response; const settings = await prisma.pageInboxAiAutomation.findUnique({ where: { pageId }, select: { enabled: true, personaName: true, salesGoal: true, instructions: true }, }); return NextResponse.json(settings ?? { enabled: false, personaName: "แอดมินพิม", salesGoal: "", instructions: "" }); } export async function PUT(req: Request, ctx: Ctx) { const { pageId } = await ctx.params; const auth = await requirePageAction(pageId, "editRules"); if (!auth.ok) return auth.response; try { const body = await readJson(req); const enabled = body.enabled === true; const personaName = str(body.personaName).trim().slice(0, 60) || "แอดมินพิม"; const salesGoal = str(body.salesGoal).trim().slice(0, 500); const instructions = str(body.instructions).trim().slice(0, 1200); if (enabled) { const profile = await prisma.pageProfile.findUnique({ where: { pageId }, select: { business: true } }); if (!profile?.business.trim()) return NextResponse.json({ error: "กรอกข้อมูลธุรกิจในโปรไฟล์เพจก่อนเปิด AI Auto" }, { status: 400 }); } const previous = await prisma.pageInboxAiAutomation.findUnique({ where: { pageId }, select: { enabled: true } }); const settings = await prisma.$transaction(async (tx) => { const saved = await tx.pageInboxAiAutomation.upsert({ where: { pageId }, create: { pageId, enabled, personaName, salesGoal, instructions, updatedById: auth.user.id }, update: { enabled, personaName, salesGoal, instructions, updatedById: auth.user.id }, }); await audit({ action: previous?.enabled !== enabled ? (enabled ? "INBOX_AI_ENABLED" : "INBOX_AI_DISABLED") : "INBOX_AI_SETTINGS_SAVED", actorId: auth.user.id, actorLabel: auth.user.name, pageId, detail: { enabled, personaName }, }, tx); return saved; }); return NextResponse.json({ enabled: settings.enabled, personaName, salesGoal, instructions }); } catch (error) { return errorResponse(error, "inbox:ai-settings"); } }