/**
 * POST /api/writing-assistant/save — Save or update a writing document.
 */
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

export async function POST(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const body = await req.json().catch(() => null);
  if (!body?.brandId || !body?.title) return NextResponse.json({ error: "brandId and title required" }, { status: 400 });

  const data = {
    brandId: body.brandId,
    title: body.title,
    content: body.content || "",
    plainText: body.plainText || "",
    targetKeyword: body.targetKeyword || null,
    secondaryKeywords: body.secondaryKeywords || [],
    briefId: body.briefId || null,
    seoScore: body.seoScore ?? null,
    llmoScore: body.llmoScore ?? null,
    humanScore: body.humanScore ?? null,
    grade: body.grade || null,
    wordCount: body.wordCount ?? null,
    status: body.status || "draft",
  };

  const doc = body.id
    ? await prisma.writingDocument.update({ where: { id: body.id }, data })
    : await prisma.writingDocument.create({ data });

  return NextResponse.json({ document: doc });
}
