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

export default defineEventHandler(async (event) => {
  try {
    await connectDB();

    const id = getRouterParam(event, "id");

    if (!id) {
      throw createError({
        statusCode: 400,
        statusMessage: "Series ID is required",
      });
    }

    // Try to fetch the Series model first for full ticketing info
    // Build query conditions based on whether id looks like ObjectId or string
    const isObjectId = /^[0-9a-fA-F]{24}$/.test(id);
    const seriesQuery = isObjectId
      ? { $or: [{ _id: id }, { id: id }, { slug: id }] }
      : { $or: [{ id: id }, { slug: id }] };

    const seriesModel = await Series.findOne(seriesQuery)
      .select("-registrations") // Don't expose registration details
      .lean();

    // Fetch all events in this series
    const events = await Event.find({
      "series.id": id,
      "series.isSeriesEvent": true,
    })
      .sort({ "series.position": 1, startDate: 1 })
      .select("-registrations")
      .lean();

    if (events.length === 0 && !seriesModel) {
      throw createError({
        statusCode: 404,
        statusMessage: "Event series not found",
      });
    }

    // Get series metadata from the Series model or the first event
    const seriesInfo = seriesModel || events[0]?.series;

    // Calculate series statistics
    const now = new Date();
    const completedEvents = events.filter((e) => e.endDate < now).length;
    const upcomingEvents = events.filter((e) => e.startDate > now).length;
    const ongoingEvents = events.filter(
      (e) => e.startDate <= now && e.endDate >= now,
    ).length;

    const firstEventDate = events[0]?.startDate;
    const lastEventDate = events[events.length - 1]?.endDate;

    // Return series with additional metadata
    return {
      id: id,
      _id: seriesModel?._id?.toString(),
      title: seriesInfo.title,
      description: seriesInfo.description,
      type: seriesInfo.type,
      totalEvents: seriesInfo.totalEvents,
      startDate: firstEventDate,
      endDate: lastEventDate,
      // Include ticketing information if it exists
      tickets: seriesModel?.tickets || null,
      events: events.map((e) => ({
        ...e,
        id: e._id.toString(),
      })),
      statistics: {
        totalEvents: events.length,
        completedEvents,
        upcomingEvents,
        ongoingEvents,
        isOngoing:
          firstEventDate && lastEventDate
            ? firstEventDate <= now && lastEventDate >= now
            : false,
        isUpcoming: firstEventDate ? firstEventDate > now : false,
        isCompleted: lastEventDate ? lastEventDate < now : false,
        totalRegistrations: events.reduce(
          (sum, e) => sum + (e.registrations?.length || 0),
          0,
        ),
      },
    };
  } catch (error) {
    console.error("Error fetching event series:", error);
    if (error.statusCode) throw error;

    throw createError({
      statusCode: 500,
      statusMessage: "Failed to fetch event series",
    });
  }
});
