// @vitest-environment jsdom
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import '@testing-library/jest-dom'

vi.mock('@/actions/products', () => ({
  updateAutoPrAction: vi.fn(),
}))

vi.mock('sonner', () => ({ toast: { error: vi.fn() } }))

import { updateAutoPrAction } from '@/actions/products'
import { AutoPrToggle } from '@/components/products/auto-pr-toggle'

const mockAction = updateAutoPrAction as ReturnType<typeof vi.fn>

beforeEach(() => {
  vi.clearAllMocks()
  mockAction.mockResolvedValue({ success: true })
})

describe('AutoPrToggle', () => {
  it('renders in off state with aria-checked=false', () => {
    render(<AutoPrToggle productId="prod-1" initialValue={false} />)
    const toggle = screen.getByRole('switch')
    expect(toggle).toHaveAttribute('aria-checked', 'false')
  })

  it('renders in on state with aria-checked=true', () => {
    render(<AutoPrToggle productId="prod-1" initialValue={true} />)
    const toggle = screen.getByRole('switch')
    expect(toggle).toHaveAttribute('aria-checked', 'true')
  })

  it('calls updateAutoPrAction with true when toggled on', async () => {
    render(<AutoPrToggle productId="prod-1" initialValue={false} />)
    fireEvent.click(screen.getByRole('switch'))
    expect(mockAction).toHaveBeenCalledWith('prod-1', true)
  })

  it('calls updateAutoPrAction with false when toggled off', async () => {
    render(<AutoPrToggle productId="prod-1" initialValue={true} />)
    fireEvent.click(screen.getByRole('switch'))
    expect(mockAction).toHaveBeenCalledWith('prod-1', false)
  })
})
