/**
 * Rate limiting types — sliding window limiter with per-product config.
 *
 * Storage: datastore-backed by default, or in-memory when RATE_LIMIT_STORE_MODE=memory.
 * Config: per-product rate limit rules loaded from RATE_LIMIT_CONFIG_JSON env
 * or defaults to sensible values.
 */

import { z } from 'zod';

export interface RateLimitRule {
  /** Max requests allowed in the window. */
  maxRequests: number;
  /** Window size in seconds. */
  windowSeconds: number;
  /** Optional: specific route prefix this rule applies to (e.g. "/api/auth"). */
  routePrefix?: string;
}

export interface RateLimitConfig {
  productId: string;
  rules: RateLimitRule[];
}

export interface RateLimitEntry {
  /** Sorted timestamps of requests within the window. */
  timestamps: number[];
}

export interface RateLimitResult {
  allowed: boolean;
  limit: number;
  remaining: number;
  resetAt: string;
  retryAfterMs?: number;
}

export const CheckRateLimitSchema = z.object({
  key: z.string().min(1),
  productId: z.string().default('lysnrai'),
  routePrefix: z.string().optional(),
});

export const RateLimitConfigSchema = z.object({
  productId: z.string().min(1),
  rules: z.array(
    z.object({
      maxRequests: z.number().int().min(1),
      windowSeconds: z.number().int().min(1),
      routePrefix: z.string().optional(),
    })
  ),
});

export type CheckRateLimitInput = z.infer<typeof CheckRateLimitSchema>;
