import Event from "../../../models/event.js";
import Series from "../../../models/series.js";
import { checkUserSeriesPass } from "../../../utils/tickets.js";

export default defineEventHandler(async (event) => {
  try {
    const eventId = getRouterParam(event, "id");
    const query = getQuery(event);
    const email = query.email;

    if (!email) {
      return {
        hasAccess: false,
        requiresSeriesPass: false,
        message: "Email parameter required",
      };
    }

    // Fetch event
    const eventDoc = await Event.findOne({
      $or: [{ _id: eventId }, { slug: eventId }],
    });

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

    // Check if event requires series ticket
    if (
      !eventDoc.tickets?.requiresSeriesTicket ||
      !eventDoc.tickets?.seriesTicketReference
    ) {
      return {
        hasAccess: true,
        requiresSeriesPass: false,
        message: "Event does not require series pass",
      };
    }

    // Fetch the series
    const series = await Series.findById(
      eventDoc.tickets.seriesTicketReference,
    );

    if (!series) {
      return {
        hasAccess: false,
        requiresSeriesPass: true,
        message: "Series not found",
      };
    }

    // Check if user has a valid series pass
    const { hasPass, registration } = checkUserSeriesPass(series, email);

    if (hasPass) {
      // Check if already registered for this specific event
      const eventRegistration = eventDoc.registrations?.find(
        (reg) =>
          reg.email.toLowerCase() === email.toLowerCase() && !reg.cancelledAt,
      );

      return {
        hasAccess: true,
        requiresSeriesPass: true,
        hasSeriesPass: true,
        alreadyRegistered: !!eventRegistration,
        registration: registration
          ? {
              ticketType: registration.ticketType,
              registeredAt: registration.registeredAt,
            }
          : null,
        series: {
          id: series.id,
          title: series.title,
          slug: series.slug,
        },
        message: "Access granted via series pass",
      };
    }

    return {
      hasAccess: false,
      requiresSeriesPass: true,
      hasSeriesPass: false,
      series: {
        id: series.id,
        title: series.title,
        slug: series.slug,
      },
      message: "Series pass required for this event",
    };
  } catch (error) {
    console.error("Error checking series access:", error);
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.statusMessage || "Failed to check series access",
    });
  }
});
