const test = require('node:test')
const assert = require('node:assert')
const {
  ensureCodeLibraryDefaultExport,
  codeLibraryHasDefaultExport,
  NO_DEFAULT_EXPORT,
} = require('../src/lib/ensure-code-library-default-export')

test('html is unchanged', () => {
  const src = '<div>hi</div>'
  const { code, didAdd } = ensureCodeLibraryDefaultExport(src, 'html')
  assert.strictEqual(code, src)
  assert.strictEqual(didAdd, false)
})

test('adds default export for PascalCase named component', () => {
  const src = `import * as React from 'react'
export function Hero() { return <div /> }
`
  const { code, didAdd } = ensureCodeLibraryDefaultExport(src, 'tsx')
  assert.strictEqual(didAdd, true)
  assert.match(code, /export default Hero/)
})

test('leaves existing default export and didAdd false', () => {
  const src = `import * as React from 'react'
export default function Hero() { return <div /> }
`
  const { code, didAdd } = ensureCodeLibraryDefaultExport(src, 'jsx')
  assert.strictEqual(didAdd, false)
  assert.match(code, /export default function Hero/)
})

test('throws when no default and no inferable component', () => {
  const src = 'export const x = 1\n'
  assert.throws(
    () => ensureCodeLibraryDefaultExport(src, 'jsx'),
    (e) => e instanceof Error && e.message === NO_DEFAULT_EXPORT,
  )
})

test('codeLibraryHasDefaultExport matches presence of default export (no rewrite)', () => {
  assert.strictEqual(
    codeLibraryHasDefaultExport(
      `export default function Hero() { return <div /> }
const title = $(sectionTitle:RichText={text: ""})
`,
      'jsx',
    ),
    true,
  )
  assert.strictEqual(codeLibraryHasDefaultExport('export const x = 1\n', 'jsx'), false)
})
