import { test } from 'node:test';
import assert from 'node:assert/strict';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';

import { register, isLazy, lookupModuleUrl } from '../../src/registry.js';
import { WebComponent } from '../../src/component.js';
import { setVendorEntries, buildImportMap, setCoreInstall } from '../../../server/src/importmap.js';

// Bind the importmap to the workspace @webjsdev/core install so the
// framework entries (e.g. `@webjsdev/core/lazy-loader`) populate.
const CORE_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
await setCoreInstall(CORE_DIR, false);

// --- Lazy flag in registry ---

test('registry: non-lazy component has lazy=false', () => {
  class EagerComp extends WebComponent {}
  register('test-eager-comp', EagerComp);
  assert.equal(isLazy('test-eager-comp'), false);
});

test('registry: lazy component has lazy=true', () => {
  class LazyComp extends WebComponent {
    static lazy = true;
  }
  register('test-lazy-comp', LazyComp);
  assert.equal(isLazy('test-lazy-comp'), true);
});

test('registry: unknown tag returns false for isLazy', () => {
  assert.equal(isLazy('nonexistent-tag'), false);
});

// --- Dynamic import map entries ---

test('setVendorEntries: adds entries to import map', async () => {
  await setVendorEntries({ 'dayjs': '/__webjs/vendor/dayjs.js' });
  const map = buildImportMap();
  assert.equal(map.imports['dayjs'], '/__webjs/vendor/dayjs.js');
  // Built-ins should still be there
  assert.equal(map.imports['@webjsdev/core'], '/__webjs/core/index-browser.js');
  // Clean up
  await setVendorEntries({});
});

test('setVendorEntries: overwrite replaces previous entries', async () => {
  await setVendorEntries({ 'pkg-a': '/a.js', 'pkg-b': '/b.js' });
  let map = buildImportMap();
  assert.ok('pkg-a' in map.imports);
  assert.ok('pkg-b' in map.imports);

  await setVendorEntries({ 'pkg-c': '/c.js' });
  map = buildImportMap();
  assert.ok(!('pkg-a' in map.imports), 'old entries should be gone');
  assert.ok('pkg-c' in map.imports);
  // Clean up
  await setVendorEntries({});
});

test('import map always includes lazy-loader entry', () => {
  const map = buildImportMap();
  assert.equal(map.imports['@webjsdev/core/lazy-loader'], '/__webjs/core/src/lazy-loader.js');
});
