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

describe('bulk invoice generation queries', () => {
  it('includes time value in preview totals', async () => {
    const allCustomers = [{ id: 'cust-1', name: 'Acme Corp' }]
    const openInvoiceRows: Array<{ customerId: string | null }> = []
    const execute = [
      [{ customer_id: 'cust-1', total_seconds: '9000', line_amount: '500.00' }],
      [{ customer_id: 'cust-1', total: '120.00' }],
      [],
    ]

    const db = {
      select: (() => {
        let call = 0
        return () => ({
          from: () => ({
            where: async () => {
              call += 1
              return call === 1 ? allCustomers : openInvoiceRows
            },
          }),
        })
      })(),
      execute: async () => execute.shift() ?? [],
    }

    const { getBulkGeneratePreview } = await import('../src/queries/invoice-generation')
    const result = await getBulkGeneratePreview(db as never, 'tenant-1', {
      periodStart: '2026-05-01',
      periodEnd: '2026-05-31',
      includeTime: true,
      includeExpenses: true,
      includeMilestones: false,
    })

    expect(result.customers).toEqual([
      expect.objectContaining({
        customerId: 'cust-1',
        timeHours: 2.5,
        expenseTotal: 120,
        invoiceTotal: 620,
      }),
    ])
  })

  it('maps import_job_results.message into job status reasons', async () => {
    const job = {
      id: 'job-1',
      tenantId: 'tenant-1',
      type: 'bulk_action',
      status: 'completed',
      totalRows: 2,
      successCount: 1,
      skippedCount: 1,
      errorCount: 0,
      columnMapping: { periodStart: '2026-05-01', periodEnd: '2026-05-31' },
    }

    const resultRows = [
      {
        status: 'success',
        message: null,
        originalData: JSON.stringify({
          customerId: 'cust-1',
          customerName: 'Acme Corp',
          invoiceNumber: 'INV-001',
        }),
      },
      {
        status: 'skipped',
        message: 'No billable items',
        originalData: JSON.stringify({
          customerId: 'cust-2',
          customerName: 'Beta Ltd',
        }),
      },
    ]

    const db = {
      select: (() => {
        let selectCall = 0
        return () => {
          const thisCall = ++selectCall
          return {
            from: () => ({
              where: () => {
                if (thisCall === 1) {
                  return { limit: async () => [job] }
                }
                return { orderBy: async () => resultRows }
              },
            }),
          }
        }
      })(),
    }

    const { getBulkGenerationJobStatus } = await import('../src/queries/invoice-generation')
    const result = await getBulkGenerationJobStatus(db as never, 'tenant-1', 'job-1')

    expect(result?.results).toEqual([
      expect.objectContaining({
        customerName: 'Acme Corp',
        status: 'created',
        invoiceNumber: 'INV-001',
      }),
      expect.objectContaining({
        customerName: 'Beta Ltd',
        status: 'skipped',
        reason: 'No billable items',
      }),
    ])
  })
})
