import { query } from "../_generated/server";
import { v } from "convex/values";

/**
 * Get all waitlists for a user
 */
export const getWaitlistsByUser = query({
  args: {
    userId: v.string(),
    limit: v.optional(v.number()),
  },
  handler: async (ctx, args) => {
    const limit = args.limit ?? 50;
    return await ctx.db
      .query("waitlists")
      .withIndex("by_userId", (q) => q.eq("userId", args.userId))
      .order("desc")
      .take(limit);
  },
});

/**
 * Get active public waitlists
 */
export const getActivePublicWaitlists = query({
  args: {
    limit: v.optional(v.number()),
  },
  handler: async (ctx, args) => {
    const limit = args.limit ?? 50;
    return await ctx.db
      .query("waitlists")
      .withIndex("by_isActive", (q) => q.eq("isActive", true))
      .filter((q) =>
        q.or(
          q.eq(q.field("isPublic"), true),
          q.eq(q.field("userId"), undefined),
        ),
      )
      .order("desc")
      .take(limit);
  },
});

/**
 * Get a single waitlist by ID
 */
export const getWaitlistById = query({
  args: { id: v.id("waitlists") },
  handler: async (ctx, args) => {
    return await ctx.db.get(args.id);
  },
});

/**
 * Get waitlist signups by waitlist ID
 */
export const getWaitlistSignups = query({
  args: {
    waitlistId: v.string(),
    limit: v.optional(v.number()),
  },
  handler: async (ctx, args) => {
    const limit = args.limit ?? 200;
    return await ctx.db
      .query("waitlist_signups")
      .withIndex("by_waitlistId", (q) => q.eq("waitlistId", args.waitlistId))
      .order("desc")
      .take(limit);
  },
});

/**
 * Count waitlist signups
 */
export const countWaitlistSignups = query({
  args: { waitlistId: v.string() },
  handler: async (ctx, args) => {
    const signups = await ctx.db
      .query("waitlist_signups")
      .withIndex("by_waitlistId", (q) => q.eq("waitlistId", args.waitlistId))
      .collect();
    return signups.length;
  },
});

/**
 * Check if email is signed up for a waitlist
 */
export const checkEmailSignup = query({
  args: {
    waitlistId: v.string(),
    email: v.string(),
  },
  handler: async (ctx, args) => {
    return await ctx.db
      .query("waitlist_signups")
      .withIndex("by_email", (q) => q.eq("email", args.email.toLowerCase()))
      .filter((q) => q.eq(q.field("waitlistId"), args.waitlistId))
      .first();
  },
});

/**
 * Get user's signed up waitlist IDs
 */
export const getUserSignupWaitlistIds = query({
  args: { userId: v.string() },
  handler: async (ctx, args) => {
    const signups = await ctx.db
      .query("waitlist_signups")
      .filter((q) => q.eq(q.field("userId"), args.userId))
      .collect();
    return signups.map((s) => s.waitlistId);
  },
});

/**
 * Get a single signup by ID
 */
export const getSignupById = query({
  args: { id: v.id("waitlist_signups") },
  handler: async (ctx, args) => {
    return await ctx.db.get(args.id);
  },
});
