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.name || !String(body.name).trim()) return fail("Name is required");
    if (!body.content || !String(body.content).trim()) return fail("Content is required");

    const rating = Math.max(1, Math.min(5, Number(body.rating) || 5));

    const testimonial = await db.testimonial.create({
      data: {
        name: String(body.name).trim(),
        position: body.position ? String(body.position).trim() : null,
        company: body.company ? String(body.company).trim() : null,
        content: String(body.content).trim(),
        rating,
        avatar: body.avatar || null,
        isEnabled: body.isEnabled ?? true,
        order: typeof body.order === "number" ? body.order : Number(body.order) || 0,
      },
    });
    return ok({ testimonial });
  } catch (e) {
    console.error(e);
    return fail("Failed to create testimonial", 500);
  }
}
