import { mutation } from "../_generated/server";
import { v } from "convex/values";
import {
  alertTypeValidator,
  alertSeverityValidator,
} from "../schema/notifications";

/**
 * Create a staff alert (e.g. NEW_DEMO, NEW_CONTACT)
 */
export const createStaffAlert = mutation({
  args: {
    type: alertTypeValidator,
    title: v.string(),
    message: v.string(),
    severity: alertSeverityValidator,
    metadata: v.optional(v.any()),
  },
  handler: async (ctx, args) => {
    return await ctx.db.insert("staff_alerts", {
      type: args.type,
      title: args.title,
      message: args.message,
      severity: args.severity,
      isRead: false,
      metadata: args.metadata,
      createdAt: Date.now(),
    });
  },
});

/**
 * Create a new notification
 * Phase 3: Notifications & Support
 */
export const create = mutation({
  args: {
    userId: v.string(),
    type: v.string(),
    title: v.string(),
    message: v.string(),
    actionUrl: v.optional(v.string()),
    metadata: v.optional(v.any()),
  },
  handler: async (ctx, args) => {
    return await ctx.db.insert("notifications", {
      userId: args.userId,
      type: args.type as
        | "new_booking"
        | "deposit_received"
        | "new_conversation"
        | "booking_reminder"
        | "system_alert"
        | "integration_error"
        | "new_lead",
      title: args.title,
      message: args.message,
      actionUrl: args.actionUrl,
      isRead: false,
      metadata: args.metadata,
      createdAt: Date.now(),
    });
  },
});

/**
 * Mark a notification as read
 * Phase 3: Notifications & Support
 */
export const markRead = mutation({
  args: { id: v.id("notifications") },
  handler: async (ctx, args) => {
    await ctx.db.patch(args.id, {
      isRead: true,
      readAt: Date.now(),
    });
  },
});

/**
 * Mark all notifications as read for a user
 * Phase 3: Notifications & Support
 */
export const markAllRead = mutation({
  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();

    const now = Date.now();
    await Promise.all(
      unread.map((n) => ctx.db.patch(n._id, { isRead: true, readAt: now })),
    );

    return { updated: unread.length };
  },
});

/**
 * Delete a notification
 * Phase 3: Notifications & Support
 */
export const deleteNotification = mutation({
  args: { id: v.id("notifications") },
  handler: async (ctx, args) => {
    await ctx.db.delete(args.id);
  },
});
