// src/hooks/mutations/useAddWatchedItemMutation.test.tsx
import { renderHook, waitFor } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { ReactNode } from 'react';
import { useAddWatchedItemMutation } from './useAddWatchedItemMutation';
import * as apiClient from '../../services/apiClient';
import * as notificationService from '../../services/notificationService';

vi.mock('../../services/apiClient');
vi.mock('../../services/notificationService');

const mockedApiClient = vi.mocked(apiClient);
const mockedNotifications = vi.mocked(notificationService);

describe('useAddWatchedItemMutation', () => {
  let queryClient: QueryClient;

  const wrapper = ({ children }: { children: ReactNode }) => (
    <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
  );

  beforeEach(() => {
    vi.resetAllMocks();
    queryClient = new QueryClient({
      defaultOptions: {
        queries: { retry: false },
        mutations: { retry: false },
      },
    });
  });

  it('should add a watched item successfully with category', async () => {
    const mockResponse = { id: 1, item_name: 'Milk', category: 'Dairy' };
    mockedApiClient.addWatchedItem.mockResolvedValue({
      ok: true,
      json: () => Promise.resolve(mockResponse),
    } as Response);

    const { result } = renderHook(() => useAddWatchedItemMutation(), { wrapper });

    result.current.mutate({ itemName: 'Milk', category: 'Dairy' });

    await waitFor(() => expect(result.current.isSuccess).toBe(true));

    expect(mockedApiClient.addWatchedItem).toHaveBeenCalledWith('Milk', 'Dairy');
    expect(mockedNotifications.notifySuccess).toHaveBeenCalledWith('Item added to watched list');
  });

  it('should add a watched item without category', async () => {
    const mockResponse = { id: 1, item_name: 'Bread' };
    mockedApiClient.addWatchedItem.mockResolvedValue({
      ok: true,
      json: () => Promise.resolve(mockResponse),
    } as Response);

    const { result } = renderHook(() => useAddWatchedItemMutation(), { wrapper });

    result.current.mutate({ itemName: 'Bread' });

    await waitFor(() => expect(result.current.isSuccess).toBe(true));

    expect(mockedApiClient.addWatchedItem).toHaveBeenCalledWith('Bread', '');
  });

  it('should invalidate watched-items query on success', async () => {
    mockedApiClient.addWatchedItem.mockResolvedValue({
      ok: true,
      json: () => Promise.resolve({ id: 1 }),
    } as Response);

    const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries');

    const { result } = renderHook(() => useAddWatchedItemMutation(), { wrapper });

    result.current.mutate({ itemName: 'Eggs' });

    await waitFor(() => expect(result.current.isSuccess).toBe(true));

    expect(invalidateQueriesSpy).toHaveBeenCalledWith({ queryKey: ['watched-items'] });
  });

  it('should handle API error with error message', async () => {
    mockedApiClient.addWatchedItem.mockResolvedValue({
      ok: false,
      status: 409,
      json: () => Promise.resolve({ message: 'Item already watched' }),
    } as Response);

    const { result } = renderHook(() => useAddWatchedItemMutation(), { wrapper });

    result.current.mutate({ itemName: 'Milk' });

    await waitFor(() => expect(result.current.isError).toBe(true));

    expect(result.current.error?.message).toBe('Item already watched');
    expect(mockedNotifications.notifyError).toHaveBeenCalledWith('Item already watched');
  });

  it('should handle API error when json parse fails', async () => {
    mockedApiClient.addWatchedItem.mockResolvedValue({
      ok: false,
      status: 500,
      json: () => Promise.reject(new Error('Parse error')),
    } as Response);

    const { result } = renderHook(() => useAddWatchedItemMutation(), { wrapper });

    result.current.mutate({ itemName: 'Cheese' });

    await waitFor(() => expect(result.current.isError).toBe(true));

    expect(result.current.error?.message).toBe('Request failed with status 500');
  });

  it('should handle API error with empty message in response', async () => {
    mockedApiClient.addWatchedItem.mockResolvedValue({
      ok: false,
      status: 400,
      json: () => Promise.resolve({ message: '' }),
    } as Response);

    const { result } = renderHook(() => useAddWatchedItemMutation(), { wrapper });

    result.current.mutate({ itemName: 'Butter' });

    await waitFor(() => expect(result.current.isError).toBe(true));

    expect(result.current.error?.message).toBe('Failed to add watched item');
  });

  it('should use fallback error message when error has no message', async () => {
    mockedApiClient.addWatchedItem.mockRejectedValue(new Error(''));

    const { result } = renderHook(() => useAddWatchedItemMutation(), { wrapper });

    result.current.mutate({ itemName: 'Yogurt' });

    await waitFor(() => expect(result.current.isError).toBe(true));

    expect(mockedNotifications.notifyError).toHaveBeenCalledWith(
      'Failed to add item to watched list',
    );
  });
});
