const test = require('node:test')
const assert = require('node:assert')
const fs = require('fs')
const path = require('path')
const os = require('os')
const { writeCmsDependenciesBoilerplate } = require('../src/lib/cms-dependencies-boilerplate')
const { depsAddCommand, depsInitCommand } = require('../src/commands/deps')

test('deps add merges a relative import into an on-disk cmsDependencies file', async () => {
  const site = fs.mkdtempSync(path.join(os.tmpdir(), 'bild-deps-cmd-'))
  const w = writeCmsDependenciesBoilerplate(site, 'src/cmsDependencies.ts')
  assert.strictEqual(w.ok, true)

  fs.mkdirSync(path.join(site, 'src', 'ui'), { recursive: true })
  fs.writeFileSync(
    path.join(site, 'src/ui/helper.tsx'),
    'export function H() { return null }\n',
    'utf8',
  )
  const comp = path.join(site, 'src/Banner.tsx')
  fs.writeFileSync(
    comp,
    `import * as React from 'react'
import { H } from './ui/helper'
export function Banner() { return <H /> }
`,
    'utf8',
  )

  const depsFile = path.join(site, 'src', 'cmsDependencies.ts')
  await depsAddCommand([comp], { sitePath: site, depsFile, dryRun: false })

  const merged = fs.readFileSync(depsFile, 'utf8')
  assert.ok(!/export \* from ['"]@\/app\/components\/Components['"]/.test(merged))
  const barrel = fs.readFileSync(path.join(site, 'src', 'app', 'components', 'Components.tsx'), 'utf8')
  assert.match(barrel, /ui\/helper/)
  assert.match(barrel, /export \{\s*H\s*\}/)
})

test('deps init writes boilerplate for sitePath + default relative path', async () => {
  const site = fs.mkdtempSync(path.join(os.tmpdir(), 'bild-deps-init-'))
  fs.mkdirSync(path.join(site, 'src'), { recursive: true })
  await depsInitCommand({ sitePath: site, depsFile: 'src/cmsDependencies.ts', force: false })
  const p = path.join(site, 'src', 'cmsDependencies.ts')
  assert.ok(fs.existsSync(p))
  assert.match(fs.readFileSync(p, 'utf8'), /getRemoteProps/)
})
