import Event from "../../models/event.js";
import { connectDB } from "../../utils/mongoose.js";

export default defineEventHandler(async (event) => {
  try {
    // Ensure database connection
    await connectDB();
    // Get query parameters for filtering
    const query = getQuery(event);
    const filter = {};

    // Only show visible events on public calendar (unless specifically requested)
    if (query.includeHidden !== "true") {
      filter.isVisible = true;
    }

    // Filter for upcoming events only if requested
    if (query.upcoming === "true") {
      filter.startDate = { $gte: new Date() };
    }

    // Filter by event type if provided
    if (query.eventType) {
      filter.eventType = query.eventType;
    }

    // Filter for members-only events
    if (query.membersOnly !== undefined) {
      filter.membersOnly = query.membersOnly === "true";
    }

    // Fetch events from database
    const events = await Event.find(filter)
      .sort({ startDate: 1 })
      .select("-registrations") // Don't expose registration details in list view
      .lean();

    // Add computed fields
    const eventsWithMeta = events.map((event) => ({
      ...event,
      id: event._id.toString(),
      registeredCount: event.registrations?.length || 0,
    }));

    return eventsWithMeta;
  } catch (error) {
    console.error("Error fetching events:", error);
    throw createError({
      statusCode: 500,
      statusMessage: "Failed to fetch events",
    });
  }
});
