import Event from "../../../models/event";

export default defineEventHandler(async (event) => {
  const id = getRouterParam(event, "id");
  const body = await validateBody(event, waitlistDeleteSchema);

  const { email } = body;

  try {
    // Find event by ID or slug
    const eventData = await Event.findOne({
      $or: [{ _id: id }, { slug: id }],
    });

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

    // Find and remove from waitlist
    const waitlistIndex = eventData.tickets?.waitlist?.entries?.findIndex(
      (entry) => entry.email.toLowerCase() === email.toLowerCase()
    );

    if (waitlistIndex === -1 || waitlistIndex === undefined) {
      throw createError({
        statusCode: 404,
        statusMessage: "You are not on the waitlist for this event",
      });
    }

    eventData.tickets.waitlist.entries.splice(waitlistIndex, 1);
    await eventData.save();

    return {
      success: true,
      message: "You have been removed from the waitlist",
    };
  } catch (error) {
    if (error.statusCode) {
      throw error;
    }

    console.error("Error leaving waitlist:", error);
    throw createError({
      statusCode: 500,
      statusMessage: "Failed to leave waitlist",
    });
  }
});
