import { prisma } from '@/lib/prisma'
import * as processor from '../processor'

jest.mock('@/lib/prisma', () => ({
  prisma: {
    download: {
      findMany: jest.fn(),
      updateMany: jest.fn(),
    },
  },
}))
jest.mock('../processor')

const mockFindMany = prisma.download.findMany as jest.Mock
const mockUpdateMany = prisma.download.updateMany as jest.Mock
const mockProcess = processor.processDownload as jest.Mock

describe('pollOnce', () => {
  beforeEach(() => {
    jest.clearAllMocks()
  })

  it('processes all PENDING downloads', async () => {
    mockFindMany.mockResolvedValue([{ id: 'dl-1' }, { id: 'dl-2' }])
    mockUpdateMany.mockResolvedValue({ count: 2 })
    mockProcess.mockResolvedValue(undefined)

    const { pollOnce } = await import('../index')
    await pollOnce()

    expect(mockUpdateMany).toHaveBeenCalledWith(
      expect.objectContaining({
        where: expect.objectContaining({ status: 'PENDING' }),
        data: expect.objectContaining({ status: 'PROCESSING' }),
      })
    )
    expect(mockProcess).toHaveBeenCalledTimes(2)
    expect(mockProcess).toHaveBeenCalledWith('dl-1')
    expect(mockProcess).toHaveBeenCalledWith('dl-2')
  })

  it('does nothing when queue is empty', async () => {
    mockFindMany.mockResolvedValue([])

    const { pollOnce } = await import('../index')
    await pollOnce()

    expect(mockUpdateMany).not.toHaveBeenCalled()
    expect(mockProcess).not.toHaveBeenCalled()
  })
})
