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

/**
 * Check whether a request is within the rate limit window.
 *
 * Returns { allowed, remaining, resetAt }.
 * Does NOT increment the counter — the caller must call
 * incrementRateLimit after confirming the request is allowed.
 */
export const checkRateLimit = query({
  args: {
    key: v.string(),
    limiterType: v.string(),
    limit: v.number(),
    windowMs: v.number(),
  },
  handler: async (ctx, args) => {
    const now = Date.now();

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

    // No record or expired window — fully allowed
    if (!existing || existing.windowEnd <= now) {
      return {
        allowed: true,
        remaining: args.limit,
        resetAt: now + args.windowMs,
      };
    }

    // Active window — check count against limit
    const remaining = Math.max(0, args.limit - existing.count);
    return {
      allowed: existing.count < args.limit,
      remaining,
      resetAt: existing.windowEnd,
    };
  },
});
