import jwt from "jsonwebtoken"; import Update from "../../models/update.js"; import { connectDB } from "../../utils/mongoose.js"; export default defineEventHandler(async (event) => { await connectDB(); const token = getCookie(event, "auth-token"); if (!token) { throw createError({ statusCode: 401, statusMessage: "Not authenticated", }); } let memberId; try { const decoded = jwt.verify(token, process.env.JWT_SECRET); memberId = decoded.memberId; } catch (err) { throw createError({ statusCode: 401, statusMessage: "Invalid or expired token", }); } const id = getRouterParam(event, "id"); const body = await readBody(event); 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", }); } });