import Update from "../../models/update.js";

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

  const id = getRouterParam(event, "id");
  const body = await validateBody(event, updatePatchSchema);

  try {
    const update = await Update.findById(id);

    if (!update) {
      throw createError({
        statusCode: 404,
        statusMessage: "Update not found",
      });
    }

    // Check if user is the author
    if (update.author.toString() !== memberId) {
      throw createError({
        statusCode: 403,
        statusMessage: "You can only edit your own updates",
      });
    }

    // Update allowed fields
    if (body.content !== undefined) update.content = body.content;
    if (body.images !== undefined) update.images = body.images;
    if (body.privacy !== undefined) update.privacy = body.privacy;
    if (body.commentsEnabled !== undefined)
      update.commentsEnabled = body.commentsEnabled;

    await update.save();
    await update.populate("author", "name avatar");

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