import { NextRequest } from "next/server";
import { db } from "@/lib/db";
import { requireAdminSession, unauthorized, ok, fail } from "@/lib/admin-api";

export async function POST(req: NextRequest) {
  const session = await requireAdminSession();
  if (!session) return unauthorized();
  try {
    const body = await req.json();
    if (!body.question || !String(body.question).trim()) return fail("Question is required");
    if (!body.answer || !String(body.answer).trim()) return fail("Answer is required");

    const faq = await db.faq.create({
      data: {
        question: String(body.question).trim(),
        answer: String(body.answer).trim(),
        category: body.category ? String(body.category).trim() : null,
        order: typeof body.order === "number" ? body.order : Number(body.order) || 0,
        isEnabled: body.isEnabled ?? true,
      },
    });
    return ok({ faq });
  } catch (e) {
    console.error(e);
    return fail("Failed to create FAQ", 500);
  }
}
