import { spawnPromisified } from '../common/index.mjs';
import * as fixtures from '../common/fixtures.mjs';
import assert from 'assert';
import { execPath } from 'node:process';
import { describe, it } from 'node:test';


describe('ESM: thenable loader hooks', { concurrency: !process.env.TEST_PARALLEL }, () => {
  it('should behave as a normal promise resolution', async () => {
    const { code, stderr } = await spawnPromisified(execPath, [
      '--experimental-loader',
      fixtures.fileURL('es-module-loaders', 'thenable-load-hook.mjs').href,
      fixtures.path('es-modules', 'test-esm-ok.mjs'),
    ]);

    assert.strictEqual(code, 0);
    assert.ok(!stderr.includes('must not call'));
  });

  it('should crash the node process rejection with an error', async () => {
    const { code, stderr } = await spawnPromisified(execPath, [
      '--experimental-loader',
      fixtures.fileURL('es-module-loaders', 'thenable-load-hook-rejected.mjs').href,
      fixtures.path('es-modules', 'test-esm-ok.mjs'),
    ]);

    assert.notStrictEqual(code, 0);
    assert.match(stderr, /\sError: must crash the process\r?\n/);
    assert.ok(!stderr.includes('must not call'));
  });

  it('should just reject without an error (but NOT crash the node process)', async () => {
    const { code, stderr } = await spawnPromisified(execPath, [
      '--experimental-loader',
      fixtures.fileURL('es-module-loaders', 'thenable-load-hook-rejected-no-arguments.mjs').href,
      fixtures.path('es-modules', 'test-esm-ok.mjs'),
    ]);

    assert.notStrictEqual(code, 0);
    assert.match(stderr, /\sundefined\r?\n/);
    assert.ok(!stderr.includes('must not call'));
  });
});
