import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, fireEvent } from '@testing-library/react'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import * as notifications from '@/shared/model/notification'
import { AddToCartButton } from '../AddToCartButton'

vi.mock('@/entities/cart/api/cart-api', () => ({
  addToCart: vi.fn(() => Promise.resolve()),
}))

vi.mock('effector-react', async () => {
  const actual = await vi.importActual('effector-react')
  return { ...actual, useUnit: () => ({ id: '1', email: 'test@test.com' }) }
})

describe('AddToCartButton', () => {
  const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })

  beforeEach(() => {
    vi.clearAllMocks()
    qc.clear()
  })

  it('calls addNotification after successful add', async () => {
    const spy = vi.spyOn(notifications, 'addNotification')
    render(
      <QueryClientProvider client={qc}>
        <AddToCartButton productId="test-product" />
      </QueryClientProvider>,
    )

    fireEvent.click(screen.getByRole('button', { name: /в корзину/i }))

    await vi.waitFor(() => {
      expect(spy).toHaveBeenCalledWith({ type: 'info', message: 'Товар добавлен в корзину' })
    })
  })
})
