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

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

  const { name, email, membershipLevel } = 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",
      });
    }

    // Check if waitlist is enabled
    if (!eventData.tickets?.waitlist?.enabled) {
      throw createError({
        statusCode: 400,
        statusMessage: "Waitlist is not enabled for this event",
      });
    }

    // Check if already on waitlist
    const existingEntry = eventData.tickets.waitlist.entries?.find(
      (entry) => entry.email.toLowerCase() === email.toLowerCase()
    );

    if (existingEntry) {
      throw createError({
        statusCode: 400,
        statusMessage: "You are already on the waitlist for this event",
      });
    }

    // Check if already registered
    const existingRegistration = eventData.registrations?.find(
      (reg) => reg.email?.toLowerCase() === email.toLowerCase() && !reg.cancelledAt
    );

    if (existingRegistration) {
      throw createError({
        statusCode: 400,
        statusMessage: "You are already registered for this event",
      });
    }

    // Check waitlist capacity
    const currentWaitlistSize = eventData.tickets.waitlist.entries?.length || 0;
    const maxSize = eventData.tickets.waitlist.maxSize;

    if (maxSize && currentWaitlistSize >= maxSize) {
      throw createError({
        statusCode: 400,
        statusMessage: "The waitlist is full",
      });
    }

    // Get member info if authenticated
    let memberName = name;
    let memberLevel = membershipLevel || "non-member";

    // Try to find member by email
    const member = await Member.findOne({ email: email.toLowerCase() });
    if (member) {
      memberName = memberName || member.name;
      memberLevel = `${member.circle}-${member.contributionTier}`;
    }

    // Add to waitlist
    if (!eventData.tickets.waitlist.entries) {
      eventData.tickets.waitlist.entries = [];
    }

    eventData.tickets.waitlist.entries.push({
      name: memberName || "Guest",
      email: email.toLowerCase(),
      membershipLevel: memberLevel,
      addedAt: new Date(),
      notified: false,
    });

    await eventData.save();

    // Get position in waitlist
    const position = eventData.tickets.waitlist.entries.length;

    return {
      success: true,
      message: "You have been added to the waitlist",
      position,
      totalWaitlisted: position,
    };
  } catch (error) {
    if (error.statusCode) {
      throw error;
    }

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