const test = require('node:test')
const assert = require('node:assert')
const path = require('node:path')

const { runCodemodOnFile } = require('../src/lib/codemod')

test('legacy $() vars tag JSX usage sites with data-bildit-var-*', () => {
  const fixture = path.resolve(
    __dirname,
    '../src/lib/codemod/__tests__/fixtures/var-usage/legacy.jsx',
  )

  const { output, fieldReport } = runCodemodOnFile(fixture, {
    cssMode: 'hybrid',
    namingStrategy: 'camelComponent',
    depsFilePath: null,
    fieldMapPath: path.join(path.dirname(fixture), '.bild', 'legacy.field-map.json'),
    groupingStyle: 'lineComments',
  })

  assert.match(output, /data-bildit-var-name=["'][^"']+["']/)
  assert.match(output, /data-bildit-var-type=["']RichText["']/)
  assert.ok((fieldReport.usageTaggedCount || 0) >= 1)
})

test('legacy: do not put data-bildit on <ul> that only wraps .map() when sole ref is inside callback', () => {
  const fixture = path.resolve(
    __dirname,
    '../src/lib/codemod/__tests__/fixtures/var-usage/legacy-map-ul.jsx',
  )

  const { output, fieldReport } = runCodemodOnFile(fixture, {
    cssMode: 'hybrid',
    namingStrategy: 'camelComponent',
    depsFilePath: null,
    fieldMapPath: path.join(path.dirname(fixture), '.bild', 'legacy.field-map.json'),
    groupingStyle: 'lineComments',
  })

  assert.ok(!/<ul[^>]*data-bildit-var-name/.test(output), 'ul must not inherit map-inner field tag')
  assert.match(output, /data-bildit-var-name=["']lineItemClass["']/)
  assert.ok((fieldReport.usageTaggedCount || 0) >= 1)
})

test('legacy: Boolean JSX usage does not get data-bildit-var-* (visual editor is for content fields)', () => {
  const fixture = path.resolve(
    __dirname,
    '../src/lib/codemod/__tests__/fixtures/var-usage/legacy-boolean-classname.jsx',
  )

  const { output, fieldReport } = runCodemodOnFile(fixture, {
    cssMode: 'hybrid',
    namingStrategy: 'camelComponent',
    depsFilePath: null,
    fieldMapPath: path.join(path.dirname(fixture), '.bild', 'legacy.field-map.json'),
    groupingStyle: 'lineComments',
  })

  assert.ok(
    !/data-bildit-var-name=["']rounded["']/.test(output),
    'Boolean field must not get visual-editor usage tags',
  )
  assert.ok(!/data-bildit-var-type=["']Boolean["']/.test(output))
})

test('v2 JSDoc @type vars tag JSX usage sites with data-bildit-var-*', () => {
  const fixture = path.resolve(
    __dirname,
    '../src/lib/codemod/__tests__/fixtures/var-usage/v2.jsx',
  )

  const { output, fieldReport } = runCodemodOnFile(fixture, {
    cssMode: 'hybrid',
    namingStrategy: 'camelComponent',
    depsFilePath: null,
    fieldMapPath: path.join(path.dirname(fixture), '.bild', 'v2.field-map.json'),
    groupingStyle: 'jsdoc',
  })

  assert.match(output, /data-bildit-var-name=["']sectionTitle["']/)
  assert.match(output, /data-bildit-var-type=["']RichText["']/)
  assert.ok((fieldReport.usageTaggedCount || 0) >= 1)
})

