import Event from "../../../models/event"; import { sendEventCancellationEmail, sendWaitlistNotificationEmail, } from "../../../utils/resend.js"; export default defineEventHandler(async (event) => { const id = getRouterParam(event, "id"); const body = await readBody(event); const { email } = body; if (!email) { throw createError({ statusCode: 400, statusMessage: "Email is required", }); } try { // Check if id is a valid ObjectId or treat as slug const isObjectId = /^[0-9a-fA-F]{24}$/.test(id); const query = isObjectId ? { $or: [{ _id: id }, { slug: id }] } : { slug: id }; const eventDoc = await Event.findOne(query); if (!eventDoc) { throw createError({ statusCode: 404, statusMessage: "Event not found", }); } // Find the registration index const registrationIndex = eventDoc.registrations.findIndex( (registration) => registration.email.toLowerCase() === email.toLowerCase(), ); if (registrationIndex === -1) { throw createError({ statusCode: 404, statusMessage: "Registration not found", }); } // Store registration data before removing (convert to plain object) const registration = { name: eventDoc.registrations[registrationIndex].name, email: eventDoc.registrations[registrationIndex].email, membershipLevel: eventDoc.registrations[registrationIndex].membershipLevel, }; // Remove the registration eventDoc.registrations.splice(registrationIndex, 1); // Update registered count eventDoc.registeredCount = eventDoc.registrations.length; await eventDoc.save(); // Send cancellation confirmation email try { const eventData = { title: eventDoc.title, slug: eventDoc.slug, _id: eventDoc._id, }; await sendEventCancellationEmail(registration, eventData); } catch (emailError) { // Log error but don't fail the cancellation console.error("Failed to send cancellation email:", emailError); } // Notify waitlisted users if waitlist is enabled and there are entries if ( eventDoc.tickets?.waitlist?.enabled && eventDoc.tickets.waitlist.entries?.length > 0 ) { try { const eventData = { title: eventDoc.title, slug: eventDoc.slug, _id: eventDoc._id, startDate: eventDoc.startDate, endDate: eventDoc.endDate, location: eventDoc.location, }; // Notify the first person on the waitlist who hasn't been notified yet const waitlistEntry = eventDoc.tickets.waitlist.entries.find( (entry) => !entry.notified ); if (waitlistEntry) { await sendWaitlistNotificationEmail(waitlistEntry, eventData); // Mark as notified waitlistEntry.notified = true; await eventDoc.save(); } } catch (waitlistError) { // Log error but don't fail the cancellation console.error("Failed to notify waitlist:", waitlistError); } } return { success: true, message: "Registration cancelled successfully", registeredCount: eventDoc.registeredCount, }; } catch (error) { console.error("Error cancelling registration:", error); // Re-throw known errors if (error.statusCode) { throw error; } throw createError({ statusCode: 500, statusMessage: "Failed to cancel registration", }); } });