const test = require('node:test')
const assert = require('node:assert')
const fs = require('fs')
const path = require('path')
const os = require('os')
const parser = require('@babel/parser')
const traverse = require('@babel/traverse').default
const { extractDependencies } = require('../src/lib/codemod/deps-extractor')

function parse(filePath, source) {
  const isTsx = filePath.endsWith('tsx') || filePath.endsWith('ts')
  return parser.parse(source, { sourceType: 'module', plugins: [isTsx ? 'typescript' : null, 'jsx'].filter(Boolean) })
}

test('warns when named import is missing from consumer cmsDependencies file', () => {
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bild-cmsval-'))
  const component = path.join(dir, 'Banner.tsx')
  const deps = path.join(dir, 'cmsDependencies.ts')
  // Boilerplate-style: only default export, no HeroFloatingLines
  fs.writeFileSync(
    deps,
    `import React from 'react'
const cmsDependencies = { react: { module: null } }
export default cmsDependencies
`,
    'utf8',
  )
  fs.writeFileSync(
    component,
    `import { HeroFloatingLines } from '@/cmsDependencies'
export function B() { return <HeroFloatingLines /> }
`,
    'utf8',
  )
  const ast = parse(component, fs.readFileSync(component, 'utf8'))
  const r = extractDependencies({
    ast,
    traverse,
    generate: () => ({}),
    filePath: component,
    depsImportAlias: '@/cmsDependencies',
    depsFilePath: deps,
  })
  const w = (r.warnings || []).filter((s) => s.includes('Not exported from') && s.includes('HeroFloatingLines'))
  assert.ok(w.length >= 1, `expected warning about missing export, got: ${r.warnings}`)
})

test('no warn when re-exported name exists in cmsDependencies file', () => {
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bild-cmsval-'))
  const component = path.join(dir, 'Banner.tsx')
  const deps = path.join(dir, 'cms.ts')
  fs.writeFileSync(
    deps,
    `import React from 'react'
export function HeroFloatingLines() { return null }
const cmsDependencies = { react: { module: React } }
export default cmsDependencies
`,
    'utf8',
  )
  fs.writeFileSync(
    component,
    `import { HeroFloatingLines } from '@/cmsDependencies'
export function B() { return <HeroFloatingLines /> }
`,
    'utf8',
  )
  const ast = parse(component, fs.readFileSync(component, 'utf8'))
  const r = extractDependencies({
    ast,
    traverse,
    generate: () => ({}),
    filePath: component,
    depsImportAlias: '@/cmsDependencies',
    depsFilePath: deps,
  })
  const bad = (r.warnings || []).filter((s) => s.includes('Not exported from') && s.includes('HeroFloatingLines'))
  assert.strictEqual(bad.length, 0, r.warnings && r.warnings.join('\n'))
})
