// src/utils/processingTimer.test.ts
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { recordProcessingTime, getAverageProcessingTime } from './processingTimer';
// Mock the logger to prevent console output during tests. This is a client-side utility test.
// Mock the logger to prevent console output during tests
vi.mock('../services/logger.client', () => ({
  logger: {
    error: vi.fn(),
  },
}));

const PROCESSING_TIMES_KEY = 'flyerProcessingTimes';

// Create an in-memory mock for localStorage
const localStorageMock = (() => {
  let store: Record<string, string> = {};
  return {
    getItem: (key: string) => store[key] || null,
    setItem: (key: string, value: string) => {
      store[key] = value.toString();
    },
    clear: () => {
      store = {};
    },
  };
})();

Object.defineProperty(window, 'localStorage', {
  value: localStorageMock,
});

describe('processingTimer', () => {
  beforeEach(() => {
    // Clear localStorage before each test to ensure isolation
    localStorage.clear();
  });

  describe('recordProcessingTime', () => {
    it('should add a new time to an empty list', () => {
      recordProcessingTime(50);
      const stored = localStorage.getItem(PROCESSING_TIMES_KEY);
      expect(JSON.parse(stored!)).toEqual([50]);
    });

    it('should add a new time to an existing list', () => {
      localStorage.setItem(PROCESSING_TIMES_KEY, JSON.stringify([40, 45]));
      recordProcessingTime(50);
      const stored = localStorage.getItem(PROCESSING_TIMES_KEY);
      expect(JSON.parse(stored!)).toEqual([40, 45, 50]);
    });

    it('should keep only the last 5 samples', () => {
      localStorage.setItem(PROCESSING_TIMES_KEY, JSON.stringify([10, 20, 30, 40, 50]));
      recordProcessingTime(60);
      const stored = localStorage.getItem(PROCESSING_TIMES_KEY);
      expect(JSON.parse(stored!)).toEqual([20, 30, 40, 50, 60]);
    });
  });

  describe('getAverageProcessingTime', () => {
    it('should return the default value of 45 if no data exists', () => {
      expect(getAverageProcessingTime()).toBe(45);
    });

    it('should return the default value if the stored data is an empty array', () => {
      localStorage.setItem(PROCESSING_TIMES_KEY, JSON.stringify([]));
      expect(getAverageProcessingTime()).toBe(45);
    });

    it('should correctly calculate the average of stored times', () => {
      localStorage.setItem(PROCESSING_TIMES_KEY, JSON.stringify([30, 40, 50]));
      // (30 + 40 + 50) / 3 = 40
      expect(getAverageProcessingTime()).toBe(40);
    });

    it('should round the average to the nearest integer', () => {
      localStorage.setItem(PROCESSING_TIMES_KEY, JSON.stringify([31, 41, 51]));
      // (31 + 41 + 51) / 3 = 41
      expect(getAverageProcessingTime()).toBe(41);
    });

    it('should return the default value if localStorage contains invalid JSON', async () => {
      localStorage.setItem(PROCESSING_TIMES_KEY, 'not-json');
      expect(getAverageProcessingTime()).toBe(45);
      // Also check that the error was logged
      const { logger } = await import('../services/logger.client');
      expect(logger.error).toHaveBeenCalled();
    });
  });
});