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

/**
 * Increment rate limit counter for a given key/type.
 * Upserts: if window exists and not expired, increments count.
 * If expired or missing, creates a new window.
 */
export const incrementRateLimit = mutation({
  args: {
    key: v.string(),
    limiterType: v.string(),
    windowMs: v.number(),
  },
  handler: async (ctx, args) => {
    const now = Date.now();

    // Look up existing window
    const existing = await ctx.db
      .query("rate_limit_windows")
      .withIndex("by_key_type", (q) =>
        q.eq("key", args.key).eq("limiterType", args.limiterType),
      )
      .first();

    if (existing && existing.windowEnd > now) {
      // Window still active — increment count
      await ctx.db.patch(existing._id, {
        count: existing.count + 1,
      });
      return { count: existing.count + 1, windowEnd: existing.windowEnd };
    }

    if (existing) {
      // Window expired — replace with new window
      await ctx.db.patch(existing._id, {
        count: 1,
        windowStart: now,
        windowEnd: now + args.windowMs,
      });
      return { count: 1, windowEnd: now + args.windowMs };
    }

    // No record — create new window
    await ctx.db.insert("rate_limit_windows", {
      key: args.key,
      limiterType: args.limiterType,
      count: 1,
      windowStart: now,
      windowEnd: now + args.windowMs,
    });
    return { count: 1, windowEnd: now + args.windowMs };
  },
});

/**
 * Reset (delete) a rate limit window — admin override.
 */
export const resetRateLimit = mutation({
  args: {
    key: v.string(),
    limiterType: v.string(),
  },
  handler: async (ctx, args) => {
    const existing = await ctx.db
      .query("rate_limit_windows")
      .withIndex("by_key_type", (q) =>
        q.eq("key", args.key).eq("limiterType", args.limiterType),
      )
      .first();

    if (existing) {
      await ctx.db.delete(existing._id);
      return { deleted: true };
    }
    return { deleted: false };
  },
});
