const fs = require('fs')
const path = require('path')
const os = require('os')
const { describe, it, before } = require('node:test')
const assert = require('node:assert/strict')
const { discoverCodeLibraryItemsFromRoot } = require('../src/commands/library-update')

describe('discoverCodeLibraryItemsFromRoot', () => {
  let tmpDir

  before(() => {
    tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bild-lib-'))
    const homepage = path.join(tmpDir, 'Homepage')
    fs.mkdirSync(homepage, { recursive: true })
    fs.writeFileSync(
      path.join(homepage, 'hero.jsx'),
      'export default function Hero() { return null; }\n',
    )
    fs.writeFileSync(
      path.join(homepage, 'hero.json'),
      JSON.stringify({
        name: 'Hero',
        description: 'Hero block',
        type: 'Homepage',
        image: 'https://example.com/preview.png',
        templateId: 'hero',
      }),
    )
  })

  it('discovers code files with sibling metadata', () => {
    const items = discoverCodeLibraryItemsFromRoot(tmpDir)
    assert.equal(items.length, 1)
    assert.equal(items[0].templateId, 'hero')
    assert.equal(items[0].type, 'Homepage')
    assert.equal(items[0].name, 'Hero')
    assert.equal(items[0].description, 'Hero block')
    assert.equal(items[0].image, 'https://example.com/preview.png')
    assert.ok(items[0].filePath.endsWith('hero.jsx'))
  })

  it('infers type from folder name when metadata has no type', () => {
    const root = fs.mkdtempSync(path.join(os.tmpdir(), 'bild-lib2-'))
    const sub = path.join(root, 'My_Type')
    fs.mkdirSync(sub, { recursive: true })
    fs.writeFileSync(path.join(sub, 'x.tsx'), 'export default function X() {}\n')
    fs.writeFileSync(path.join(sub, 'x.json'), JSON.stringify({ templateId: 'x' }))
    const items = discoverCodeLibraryItemsFromRoot(root)
    assert.equal(items.length, 1)
    assert.equal(items[0].type, 'My Type')
  })
})
