/**
 * Tests for per-product rate limiting.
 */

import { describe, it, expect, beforeEach, vi } from 'vitest';
import {
  checkProductRateLimit,
  getProductRateLimitStatus,
  getRateLimitSummary,
  resetProductRateLimit,
  cleanupRateLimitStore,
  stopRateLimitCleanup,
} from './product-rate-limit.js';

describe('product-rate-limit', () => {
  const PRODUCT_ID = 'test-product';

  beforeEach(() => {
    // Stop auto-cleanup and reset state before each test
    stopRateLimitCleanup();
    resetProductRateLimit(PRODUCT_ID);
    vi.restoreAllMocks();
  });

  describe('checkProductRateLimit', () => {
    it('allows first request', () => {
      const result = checkProductRateLimit(PRODUCT_ID);
      expect(result.allowed).toBe(true);
      expect(result.remaining).toBeGreaterThan(0);
    });

    it('tracks request count', () => {
      checkProductRateLimit(PRODUCT_ID);
      checkProductRateLimit(PRODUCT_ID);
      const result = checkProductRateLimit(PRODUCT_ID);

      expect(result.allowed).toBe(true);
      expect(result.remaining).toBeLessThan(100);
    });

    it('blocks when limit exceeded', () => {
      // Make 100 requests (default limit)
      for (let i = 0; i < 100; i++) {
        checkProductRateLimit(PRODUCT_ID);
      }

      const result = checkProductRateLimit(PRODUCT_ID);
      expect(result.allowed).toBe(false);
      expect(result.remaining).toBe(0);
    });

    it('includes reset time in response', () => {
      const result = checkProductRateLimit(PRODUCT_ID);
      expect(result.resetAt).toBeGreaterThan(Date.now());
      expect(result.resetAt).toBeLessThanOrEqual(Date.now() + 60000);
    });

    it('includes retry after when blocked', () => {
      // Exhaust limit
      for (let i = 0; i < 100; i++) {
        checkProductRateLimit(PRODUCT_ID);
      }

      const result = checkProductRateLimit(PRODUCT_ID);
      expect(result.allowed).toBe(false);
      expect(result.retryAfter).toBeDefined();
      expect(result.retryAfter).toBeGreaterThan(0);
      expect(result.retryAfter).toBeLessThanOrEqual(60);
    });
  });

  describe('getProductRateLimitStatus', () => {
    it('returns current status without incrementing', () => {
      // Use up some quota
      for (let i = 0; i < 10; i++) {
        checkProductRateLimit(PRODUCT_ID);
      }

      const status1 = getProductRateLimitStatus(PRODUCT_ID);
      const status2 = getProductRateLimitStatus(PRODUCT_ID);

      expect(status1.remaining).toBe(status2.remaining);
    });

    it('returns full quota for new product', () => {
      const result = getProductRateLimitStatus('brand-new-product');
      expect(result.allowed).toBe(true);
      expect(result.remaining).toBe(100);
    });
  });

  describe('getRateLimitSummary', () => {
    it('returns empty summary initially', () => {
      const summary = getRateLimitSummary();
      expect(summary.totalProducts).toBe(0);
      expect(summary.products).toEqual([]);
    });

    it('includes products that have made requests', () => {
      checkProductRateLimit('product-a');
      checkProductRateLimit('product-b');

      const summary = getRateLimitSummary();
      expect(summary.totalProducts).toBe(2);
      expect(summary.products.map(p => p.productId)).toContain('product-a');
      expect(summary.products.map(p => p.productId)).toContain('product-b');
    });

    it('aggregates requests per product', () => {
      // Reset to ensure clean state
      resetProductRateLimit('product-a');

      checkProductRateLimit('product-a');
      checkProductRateLimit('product-a');
      checkProductRateLimit('product-a');

      const summary = getRateLimitSummary();
      const productA = summary.products.find(p => p.productId === 'product-a');
      expect(productA?.requests).toBe(3);
    });
  });

  describe('resetProductRateLimit', () => {
    it('clears rate limit for product', () => {
      // Use up quota
      for (let i = 0; i < 100; i++) {
        checkProductRateLimit(PRODUCT_ID);
      }

      const beforeReset = checkProductRateLimit(PRODUCT_ID);
      expect(beforeReset.allowed).toBe(false);

      resetProductRateLimit(PRODUCT_ID);

      const afterReset = checkProductRateLimit(PRODUCT_ID);
      expect(afterReset.allowed).toBe(true);
      expect(afterReset.remaining).toBe(99);
    });
  });

  describe('cleanupRateLimitStore', () => {
    it('removes expired entries', () => {
      // Create some entries
      checkProductRateLimit('old-product');

      // Fast forward time to expire entries
      vi.useFakeTimers();
      vi.advanceTimersByTime(60001);

      const cleaned = cleanupRateLimitStore();
      expect(cleaned).toBeGreaterThanOrEqual(0);

      vi.useRealTimers();
    });

    it('keeps current entries', () => {
      checkProductRateLimit(PRODUCT_ID);

      const cleaned = cleanupRateLimitStore();
      expect(cleaned).toBe(0);
    });
  });

  describe('rate limiting per product isolation', () => {
    it('isolates limits between products', () => {
      // Exhaust limit for product A
      for (let i = 0; i < 100; i++) {
        checkProductRateLimit('product-a');
      }

      // Product B should still have quota
      const productBResult = checkProductRateLimit('product-b');
      expect(productBResult.allowed).toBe(true);
      expect(productBResult.remaining).toBe(99);
    });
  });
});
