import Update from "../../models/update.js";
import { validateBody } from "../../utils/validateBody.js";
import { updateCreateSchema } from "../../utils/schemas.js";

export default defineEventHandler(async (event) => {
  const member = await requireAuth(event);
  const memberId = member._id.toString();

  const body = await validateBody(event, updateCreateSchema);

  try {
    const update = await Update.create({
      author: memberId,
      content: body.content,
      images: body.images || [],
      privacy: body.privacy || "members",
      commentsEnabled: body.commentsEnabled ?? true,
    });

    // Populate author details
    await update.populate("author", "name avatar");

    return update;
  } catch (error) {
    if (error.statusCode) throw error;
    console.error("Create update error:", error);
    throw createError({
      statusCode: 500,
      statusMessage: "Failed to create update",
    });
  }
});
