import { describe, it, expect, beforeEach, vi } from 'vitest'
import { createFormulaDownloadConfig } from './download'
import type { FormulaWidgetData } from './types'

let csvText = ''

beforeEach(() => {
  csvText = ''
  vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:mock')
  vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined)
  const RealBlob = global.Blob
  vi.stubGlobal(
    'Blob',
    class extends RealBlob {
      constructor(parts: BlobPart[], opts?: BlobPropertyBag) {
        csvText = typeof parts[0] === 'string' ? parts[0] : ''
        super(parts, opts)
      }
    },
  )
})

describe('createFormulaDownloadConfig', () => {
  it('CSV-only by default', () => {
    const items = createFormulaDownloadConfig({
      filename: 'f',
      getData: () => [{ value: 1 }],
    })
    expect(items.map((i) => i.id)).toEqual(['csv'])
    expect(items[0]?.label).toBe('CSV')
    expect(items[0]?.icon).toBeTruthy()
  })

  it('prepends PNG when getCaptureEl is provided', () => {
    const items = createFormulaDownloadConfig({
      filename: 'f',
      getData: () => [],
      getCaptureEl: () => document.createElement('div'),
    })
    expect(items.map((i) => i.id)).toEqual(['png', 'csv'])
  })

  it('CSV resolve serialises all optional fields, defaulting blanks', async () => {
    const data: FormulaWidgetData = [
      {
        value: 42,
        prefix: '$',
        suffix: 'k',
        note: 'q1',
        series: { name: 'Rev' },
        delta: { value: 12 },
      },
      { value: 10 },
    ]
    const items = createFormulaDownloadConfig({
      filename: 'f',
      getData: () => data,
    })
    const handle = await items.find((i) => i.id === 'csv')!.resolve()
    expect(handle.filename).toBe('f.csv')
    expect(csvText).toBe(
      'series,prefix,value,suffix,note,delta\nRev,$,42,k,q1,12\n,,10,,,',
    )
  })
})
