// src/hooks/mutations/useRemoveWatchedItemMutation.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 { useRemoveWatchedItemMutation } from './useRemoveWatchedItemMutation';
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('useRemoveWatchedItemMutation', () => {
  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 remove a watched item successfully', async () => {
    const mockResponse = { success: true };
    mockedApiClient.removeWatchedItem.mockResolvedValue({
      ok: true,
      json: () => Promise.resolve(mockResponse),
    } as Response);

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

    result.current.mutate({ masterItemId: 123 });

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

    expect(mockedApiClient.removeWatchedItem).toHaveBeenCalledWith(123);
    expect(mockedNotifications.notifySuccess).toHaveBeenCalledWith(
      'Item removed from watched list',
    );
  });

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

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

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

    result.current.mutate({ masterItemId: 456 });

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

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

  it('should handle API error with error message', async () => {
    mockedApiClient.removeWatchedItem.mockResolvedValue({
      ok: false,
      status: 404,
      json: () => Promise.resolve({ message: 'Watched item not found' }),
    } as Response);

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

    result.current.mutate({ masterItemId: 999 });

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

    expect(result.current.error?.message).toBe('Watched item not found');
    expect(mockedNotifications.notifyError).toHaveBeenCalledWith('Watched item not found');
  });

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

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

    result.current.mutate({ masterItemId: 123 });

    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.removeWatchedItem.mockResolvedValue({
      ok: false,
      status: 400,
      json: () => Promise.resolve({ message: '' }),
    } as Response);

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

    result.current.mutate({ masterItemId: 222 });

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

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

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

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

    result.current.mutate({ masterItemId: 321 });

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

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