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");

  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 delete your own updates",
      });
    }

    await Update.findByIdAndDelete(id);

    return { success: true };
  } catch (error) {
    if (error.statusCode) throw error;
    console.error("Delete update error:", error);
    throw createError({
      statusCode: 500,
      statusMessage: "Failed to delete update",
    });
  }
});
