import { act, renderHook } from '@testing-library/react-hooks';
import { useTimer } from '../use-timer';

describe('useTimer hook', () => {
  const defaultValue = 60;

  beforeEach(() => jest.useFakeTimers());
  afterEach(() => {
    jest.runOnlyPendingTimers();
    jest.useRealTimers();
  });

  test('defaultValue works correctly', async () => {
    const { result } = renderHook(() => useTimer(defaultValue));
    expect(result.current.timeLeft).toBe(defaultValue);
  });

  test('tick works correctly', async () => {
    const { result } = renderHook(() => useTimer(defaultValue));
    expect(result.current.timeLeft).toBe(defaultValue);

    for (let i = 0; i <= defaultValue; i++) {
      act(() => jest.advanceTimersToNextTimer(1));
      expect(result.current.timeLeft).toBe(Math.max(defaultValue - i - 1, 0));
    }
  });

  test('resetTimeLeft works correctly', async () => {
    const { result } = renderHook(() => useTimer(defaultValue));
    expect(result.current.timeLeft).toBe(defaultValue);

    act(() => jest.advanceTimersToNextTimer(defaultValue));
    expect(result.current.timeLeft).toBe(0);

    act(() => result.current.resetTimeLeft());
    expect(result.current.timeLeft).toBe(defaultValue);
  });

  test('setTimeLeft works correctly', async () => {
    const otherTimeLeft = 30;
    const { result } = renderHook(() => useTimer(defaultValue));
    expect(result.current.timeLeft).toBe(defaultValue);

    act(() => result.current.setTimeLeft(otherTimeLeft));
    expect(result.current.timeLeft).toBe(otherTimeLeft);
  });
});
