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

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

    // Fetch all series
    const series = await Series.find({ isActive: true })
      .sort({ createdAt: -1 })
      .lean();

    // For each series, get event count and statistics
    const seriesWithStats = await Promise.all(
      series.map(async (s) => {
        const events = await Event.find({
          "series.id": s.id,
          "series.isSeriesEvent": true,
        })
          .sort({ "series.position": 1, startDate: 1 })
          .lean();

        const now = new Date();
        const eventCount = events.length;
        const completedEvents = events.filter((e) => e.endDate < now).length;
        const upcomingEvents = events.filter((e) => e.startDate > now).length;

        const firstEventDate =
          events.length > 0
            ? Math.min(...events.map((e) => new Date(e.startDate)))
            : null;
        const lastEventDate =
          events.length > 0
            ? Math.max(...events.map((e) => new Date(e.endDate)))
            : null;

        let status = "upcoming";
        if (lastEventDate && lastEventDate < now) {
          status = "completed";
        } else if (
          firstEventDate &&
          firstEventDate <= now &&
          lastEventDate &&
          lastEventDate >= now
        ) {
          status = "active";
        }

        return {
          ...s,
          events, // Include full event objects
          eventCount,
          completedEvents,
          upcomingEvents,
          startDate: firstEventDate,
          endDate: lastEventDate,
          status,
          totalRegistrations: events.reduce(
            (sum, e) => sum + (e.registrations?.length || 0),
            0,
          ),
        };
      }),
    );

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