// Simple in-memory rate limiter
// For production, consider using Redis or a similar solution

interface RateLimitEntry {
  count: number
  resetTime: number
}

const rateLimitStore = new Map<string, RateLimitEntry>()

// Configuration for different endpoints
const RATE_LIMIT_CONFIG = {
  'contact-form': {
    maxRequests: 5, // Max 5 requests
    windowMs: 15 * 60 * 1000, // Per 15 minutes
  },
  'newsletter': {
    maxRequests: 3, // Max 3 requests
    windowMs: 60 * 60 * 1000, // Per hour
  },
  'api-general': {
    maxRequests: 100, // Max 100 requests
    windowMs: 15 * 60 * 1000, // Per 15 minutes
  },
}

type RateLimitType = keyof typeof RATE_LIMIT_CONFIG

export async function rateLimit(
  identifier: string,
  type: RateLimitType = 'api-general'
): Promise<{ success: boolean; remaining: number; retryAfter?: number }> {
  const config = RATE_LIMIT_CONFIG[type]
  const key = `${type}:${identifier}`
  const now = Date.now()

  // Clean up old entries periodically (simple garbage collection)
  if (Math.random() < 0.01) {
    // 1% chance
    cleanupOldEntries()
  }

  // Get or create entry
  let entry = rateLimitStore.get(key)

  // Reset if window has expired
  if (!entry || now > entry.resetTime) {
    entry = {
      count: 0,
      resetTime: now + config.windowMs,
    }
    rateLimitStore.set(key, entry)
  }

  // Increment request count
  entry.count++

  // Check if limit exceeded
  if (entry.count > config.maxRequests) {
    const retryAfter = Math.ceil((entry.resetTime - now) / 1000) // in seconds
    
    return {
      success: false,
      remaining: 0,
      retryAfter,
    }
  }

  return {
    success: true,
    remaining: config.maxRequests - entry.count,
  }
}

// Clean up entries that are past their reset time
function cleanupOldEntries() {
  const now = Date.now()
  const keysToDelete: string[] = []

  rateLimitStore.forEach((entry, key) => {
    if (now > entry.resetTime) {
      keysToDelete.push(key)
    }
  })

  keysToDelete.forEach(key => rateLimitStore.delete(key))

  if (keysToDelete.length > 0) {
    console.log(`🧹 Cleaned up ${keysToDelete.length} old rate limit entries`)
  }
}

// Get rate limit info without incrementing
export function getRateLimitInfo(
  identifier: string,
  type: RateLimitType = 'api-general'
): { remaining: number; resetTime: number } {
  const config = RATE_LIMIT_CONFIG[type]
  const key = `${type}:${identifier}`
  const now = Date.now()
  
  const entry = rateLimitStore.get(key)

  if (!entry || now > entry.resetTime) {
    return {
      remaining: config.maxRequests,
      resetTime: now + config.windowMs,
    }
  }

  return {
    remaining: Math.max(0, config.maxRequests - entry.count),
    resetTime: entry.resetTime,
  }
}

// Reset rate limit for a specific identifier
export function resetRateLimit(identifier: string, type: RateLimitType = 'api-general') {
  const key = `${type}:${identifier}`
  rateLimitStore.delete(key)
}

// Clear all rate limits (for testing purposes)
export function clearAllRateLimits() {
  rateLimitStore.clear()
}

// Get statistics
export function getRateLimitStats() {
  return {
    totalEntries: rateLimitStore.size,
    entries: Array.from(rateLimitStore.entries()).map(([key, entry]) => ({
      key,
      count: entry.count,
      resetTime: new Date(entry.resetTime).toISOString(),
    })),
  }
}

