import { describe, expect, it } from 'vitest'
import ExcelJS from 'exceljs'
import type { InventoryReportRow } from '@zync/types'

import { buildInventoryCountCsv, buildInventoryCountWorkbook } from '../src/routes/reports/inventory'

describe('inventory reports export', () => {
  it('builds a sanitized count csv with quantity and valuation columns', () => {
    const csv = buildInventoryCountCsv([
      {
        productId: 'product-1',
        productName: '=Paper',
        stockItemId: 'stock-1',
        locationId: 'location-1',
        locationName: 'Main Warehouse',
        locationCode: 'MAIN',
        category: 'Office',
        unit: 'unit',
        quantityOnHand: 10,
        avgUnitCost: 12.5,
        valuationAmount: 125,
        cogsAmount: 30,
      } satisfies InventoryReportRow,
    ])

    expect(csv).toContain('Product')
    expect(csv).toContain("'=Paper")
    expect(csv).toContain('10.00')
    expect(csv).toContain('125.00')
  })

  it('builds a sanitized count workbook with quantity and valuation columns', async () => {
    const bytes = await buildInventoryCountWorkbook([
      {
        productId: 'product-1',
        productName: '=Paper',
        stockItemId: 'stock-1',
        locationId: 'location-1',
        locationName: 'Main Warehouse',
        locationCode: 'MAIN',
        category: 'Office',
        unit: 'unit',
        quantityOnHand: 10,
        avgUnitCost: 12.5,
        valuationAmount: 125,
        cogsAmount: 30,
      } satisfies InventoryReportRow,
    ])

    const workbook = new ExcelJS.Workbook()
    await workbook.xlsx.load(Buffer.from(bytes))
    const sheet = workbook.getWorksheet('Inventory Count')

    expect(sheet).toBeDefined()
    expect(sheet?.getRow(1).values).toEqual([
      ,
      'Product',
      'Stock item ID',
      'Location',
      'Location code',
      'Category',
      'Unit',
      'Quantity on hand',
      'Average unit cost',
      'Valuation amount',
      'COGS in range',
    ])
    expect(sheet?.getCell('A2').value).toBe("'=Paper")
    expect(sheet?.getCell('F2').value).toBe('unit')
    expect(sheet?.getCell('G2').value).toBe(10)
    expect(sheet?.getCell('H2').value).toBe(12.5)
    expect(sheet?.getCell('I2').value).toBe(125)
  })
})
