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

/**
 * Get notifications for a user (paginated)
 * Phase 3: Notifications & Support
 */
export const getNotifications = query({
  args: {
    userId: v.string(),
    limit: v.optional(v.number()),
    isRead: v.optional(v.boolean()),
  },
  handler: async (ctx, args) => {
    const limit = args.limit ?? 20;
    let q = ctx.db
      .query("notifications")
      .withIndex("by_userId_createdAt", (q) => q.eq("userId", args.userId));

    if (args.isRead !== undefined) {
      q = q.filter((f) => f.eq(f.field("isRead"), args.isRead));
    }

    return await q.order("desc").take(limit);
  },
});

/**
 * Get unread notification count for a user
 * Phase 3: Notifications & Support
 */
export const getUnreadCount = query({
  args: { userId: v.string() },
  handler: async (ctx, args) => {
    const unread = await ctx.db
      .query("notifications")
      .withIndex("by_userId_isRead", (q: any) =>
        q.eq("userId", args.userId).eq("isRead", false),
      )
      .collect();
    return unread.length;
  },
});

/**
 * Get admin notifications (system-wide alerts)
 * Phase 3: Notifications & Support
 */
export const getAdminNotifications = query({
  args: {
    limit: v.optional(v.number()),
    isRead: v.optional(v.boolean()),
  },
  handler: async (ctx, args) => {
    const limit = args.limit ?? 20;
    let q = ctx.db.query("admin_notifications");

    if (args.isRead !== undefined) {
      q = q.filter((f) => f.eq(f.field("isRead"), args.isRead));
    }

    return await q.order("desc").take(limit);
  },
});
