import Member from "../../../../models/member.js";
import { connectDB } from "../../../../utils/mongoose.js";

/**
 * POST /api/events/[id]/tickets/check-eligibility
 * Check if a user is eligible for member pricing
 * Body: { email }
 */
export default defineEventHandler(async (event) => {
  try {
    await connectDB();
    const body = await validateBody(event, ticketEligibilitySchema);

    // Check if user is a member
    const member = await Member.findOne({
      email: body.email.toLowerCase(),
    }).select("email name circle contributionTier");

    if (!member) {
      return {
        isMember: false,
        eligibleForMemberPricing: false,
      };
    }

    return {
      isMember: true,
      eligibleForMemberPricing: true,
      memberInfo: {
        circle: member.circle,
        tier: member.contributionTier,
        name: member.name,
      },
    };
  } catch (error) {
    console.error("Error checking eligibility:", error);

    if (error.statusCode) {
      throw error;
    }

    throw createError({
      statusCode: 500,
      statusMessage: "Failed to check eligibility",
    });
  }
});
