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

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

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

  beforeEach(async () => {
    stopRateLimitCleanup();
    await clearAllProductRateLimits();
    await resetProductRateLimit(PRODUCT_ID);
    vi.restoreAllMocks();
  });

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

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

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

    it('blocks when limit exceeded', async () => {
      for (let i = 0; i < 100; i++) {
        await checkProductRateLimit(PRODUCT_ID);
      }

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

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

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

      const result = await 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', async () => {
      for (let i = 0; i < 10; i++) {
        await checkProductRateLimit(PRODUCT_ID);
      }

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

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

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

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

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

      const summary = await 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', async () => {
      await resetProductRateLimit('product-a');

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

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

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

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

      await resetProductRateLimit(PRODUCT_ID);

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

  describe('cleanupRateLimitStore', () => {
    it('removes expired entries', async () => {
      await checkProductRateLimit('old-product');

      vi.useFakeTimers();
      vi.advanceTimersByTime(60001);

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

      vi.useRealTimers();
    });

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

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

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

      const productBResult = await checkProductRateLimit('product-b');
      expect(productBResult.allowed).toBe(true);
      expect(productBResult.remaining).toBe(99);
    });
  });
});
