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.position || !String(body.position).trim()) return fail("Position is required");

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