import { Id } from "./_generated/dataModel";
import { mutation, query } from "./_generated/server";
import { v } from "convex/values";

export const addNotification = mutation({
  args: { 
    content: v.string(),
    buttonText: v.string(),
    buttonUrl: v.string(),
    recipients: v.array(v.id("members")),
  },
  handler: async (ctx, args) => { 
    const notificationId = await ctx.db.insert("notifications", {
      content: args.content,
      buttonText: args.buttonText,
      buttonUrl: args.buttonUrl,
      recipients: args.recipients
    });

    for (const userId of args.recipients) {
      const user = await ctx.db.get(userId);
      const currentNotifications = user?.notifications || [];
      await ctx.db.patch(userId, {
        notifications: [...currentNotifications, notificationId],
      });
    }

    return notificationId;
  },
});


export const getAllNotifications = query({
  args: { userId: v.id("members") },
  handler: async (ctx, args) => {
    // Fetch all notifications
    const notifications = await ctx.db
      .query("notifications")
      .order("desc")
      .collect();

    // Filter in memory
    const filteredNotifications = notifications.filter((notification) =>
      notification.recipients.includes(args.userId)
    );

    return filteredNotifications;
  },
});