package middleware

import (
	"context"
	"fmt"
	"time"

	"lune/talentscale/infra/cache"
	"github.com/gofiber/fiber/v2"
)

func RateLimiter(limit int, window time.Duration, keyPrefix string) fiber.Handler {
	return func(c *fiber.Ctx) error {
		// Fallback: if Redis is down, allow request
		if cache.Client == nil {
			return c.Next()
		}

		// Identification: Use IP or UserID
		identifier := c.IP()
		if userID := c.Locals("user_id"); userID != nil {
			identifier = fmt.Sprintf("%v", userID)
		}

		key := fmt.Sprintf("rate_limit:%s:%s", keyPrefix, identifier)
		
		ctx := context.Background()
		
		// Use a simple increment and expire for rate limiting
		// For more precision, sliding window could be implemented
		count, err := cache.Client.Incr(ctx, key).Result()
		if err != nil {
			// Fallback: allow request on redis error
			return c.Next()
		}

		if count == 1 {
			cache.Client.Expire(ctx, key, window)
		}

		if count > int64(limit) {
			return c.Status(fiber.StatusTooManyRequests).JSON(fiber.Map{
				"success": false,
				"message": "Too many requests. Please try again later.",
			})
		}

		return c.Next()
	}
}
