import { describe, it, expect, beforeEach, vi } from 'vitest';
import { renderHook, act, waitFor } from '@testing-library/react';
import { useItemSearch } from '../hooks/useItemSearch';

describe('useItemSearch', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    global.fetch = vi.fn();
  });

  it('initializes with idle state', () => {
    const { result } = renderHook(() => useItemSearch());
    expect(result.current.state.searchStatus).toBe('idle');
    expect(result.current.state.isSearching).toBe(false);
  });

  it('performs search with part number and category', async () => {
    global.fetch = vi.fn().mockResolvedValue({
      ok: true,
      json: async () => ({ type: 'DDR4', description: 'Kingston RAM' }),
    });

    const { result } = renderHook(() => useItemSearch());

    await act(async () => {
      await result.current.performSearch('KF466C40RS-16', 'DDR4');
    });

    expect(result.current.state.searchStatus).toBe('success');
    expect(result.current.state.searchResults?.type).toBe('DDR4');
  });

  it('handles search timeout', async () => {
    global.fetch = vi.fn().mockImplementation(
      () =>
        new Promise((_, reject) => {
          setTimeout(() => reject(new DOMException('Aborted', 'AbortError')), 100);
        })
    );

    const { result } = renderHook(() => useItemSearch({ timeout: 50 }));

    await act(async () => {
      await result.current.performSearch('KF466C40RS-16', 'DDR4');
    });

    await waitFor(() => {
      expect(result.current.state.searchStatus).toBe('timeout');
    });
  });

  it('skips search when part number is missing', async () => {
    const { result } = renderHook(() => useItemSearch());

    await act(async () => {
      await result.current.performSearch('', 'DDR4');
    });

    expect(result.current.state.searchStatus).toBe('skipped');
  });

  it('handles search error', async () => {
    global.fetch = vi.fn().mockResolvedValue({
      ok: false,
      status: 500,
    });

    const { result } = renderHook(() => useItemSearch());

    await act(async () => {
      await result.current.performSearch('KF466C40RS-16', 'DDR4');
    });

    expect(result.current.state.searchStatus).toBe('error');
    expect(result.current.state.searchError).toBeTruthy();
  });

  it('retries search', async () => {
    const { result } = renderHook(() => useItemSearch({ maxRetries: 2 }));

    global.fetch = vi.fn().mockResolvedValue({
      ok: true,
      json: async () => ({ type: 'DDR4' }),
    });

    await act(async () => {
      await result.current.retrySearch('KF466C40RS-16', 'DDR4');
    });

    expect(result.current.state.retryCount).toBe(1);
  });

  it('skips search', async () => {
    const { result } = renderHook(() => useItemSearch());

    act(() => {
      result.current.skipSearch();
    });

    expect(result.current.state.searchStatus).toBe('skipped');
    expect(result.current.state.isSearching).toBe(false);
  });
});
