use strict;
use warnings;
use Test::More tests => 8;
use Debian::PkgJs::AutoTransform;

my $bundle = './dhnodejsBundle.cjs';
my $f      = \&Debian::PkgJs::AutoTransform::_inject_require;

# A string entry point is wrapped as the "import" condition.
is_deeply $f->( './index.js', $bundle ),
  { import => './index.js', require => $bundle },
  'string entry point becomes import + require';

# A lone top-level "default" is renamed to "import" so it no longer shadows
# the injected "require".
is_deeply $f->( { default => './index.js' }, $bundle ),
  { import => './index.js', require => $bundle },
  'lone default is renamed to import';

# Other conditions are preserved while "default" is moved out of require()'s way.
is_deeply $f->( { types => './index.d.ts', default => './index.js' }, $bundle ),
  { types => './index.d.ts', import => './index.js', require => $bundle },
  'default renamed, sibling conditions kept';

# An existing "import" is kept; the redundant "default" is dropped.
is_deeply $f->( { import => './a.mjs', default => './b.mjs' }, $bundle ),
  { import => './a.mjs', require => $bundle },
  'existing import kept, default dropped';

# "node" also matches require() and sorts before it: with several shadowing
# conditions the whole set is nested under "import" so import() still resolves
# them while require() reaches the bundle.
is_deeply $f->( { node => './n.mjs', default => './d.mjs' }, $bundle ),
  { import => { node => './n.mjs', default => './d.mjs' }, require => $bundle },
  'node + default nested under import so require wins';

# A lone "node" condition would shadow require() too; nest it.
is_deeply $f->( { node => './n.mjs' }, $bundle ),
  { import => { node => './n.mjs' }, require => $bundle },
  'lone node is nested under import';

# Subpath map: the bundle is attached to the "." entry, other subpaths untouched.
is_deeply
  $f->( { '.' => { default => './index.js' }, './x' => './x.js' }, $bundle ),
  { '.' => { import => './index.js', require => $bundle }, './x' => './x.js' },
  'subpath map: require added under "."';

# A subpath map without a "." entry has nowhere to put the bundle.
eval { $f->( { './x' => './x.js' }, $bundle ) };
like $@, qr/no "\." entry/, 'subpath map without "." is rejected';
