import { describe, expect, it, vi } from 'vitest'

describe('listImportJobs', () => {
  it('uses the cursor row to fetch the next page in created_at desc order', async () => {
    const cursorLimit = vi.fn().mockResolvedValueOnce([
      { createdAt: new Date('2026-06-01T12:00:00.000Z'), id: 'job-2' },
    ])
    const pageLimit = vi.fn().mockResolvedValueOnce([
      {
        id: 'job-1',
        tenantId: 'tenant-1',
        createdBy: 'user-1',
        type: 'customers',
        status: 'completed',
        r2Key: 'tenant-1/imports/job-1-customers.csv',
        originalFilename: 'customers.csv',
        mimeType: 'text/csv',
        fileSizeBytes: 512,
        columnMapping: null,
        totalRows: 10,
        rowsProcessed: 10,
        successCount: 9,
        skippedCount: 1,
        errorCount: 0,
        startedAt: new Date('2026-06-01T12:00:01.000Z'),
        completedAt: new Date('2026-06-01T12:00:05.000Z'),
        errorMessage: null,
        createdAt: new Date('2026-06-01T11:59:00.000Z'),
        updatedAt: new Date('2026-06-01T12:00:05.000Z'),
      },
    ])

    const cursorWhere = vi.fn(() => ({ limit: cursorLimit }))
    const cursorFrom = vi.fn(() => ({ where: cursorWhere }))

    const pageOrderBy = vi.fn(() => ({ limit: pageLimit }))
    const pageWhere = vi.fn(() => ({ orderBy: pageOrderBy }))
    const pageFrom = vi.fn(() => ({ where: pageWhere }))

    const select = vi
      .fn()
      .mockImplementationOnce(() => ({ from: cursorFrom }))
      .mockImplementationOnce(() => ({ from: pageFrom }))
    const db = { select } as never

    const { listImportJobs } = await import('../../src/queries/data-import')
    const result = await listImportJobs(db, 'tenant-1', 1, 'job-2')

    expect(result).toHaveLength(1)
    expect(result[0]?.id).toBe('job-1')
    expect(select).toHaveBeenCalledTimes(2)
    expect(cursorWhere).toHaveBeenCalledTimes(1)
    expect(pageWhere).toHaveBeenCalledTimes(1)
    expect(pageOrderBy).toHaveBeenCalledTimes(1)
  })
})
