'use strict';

const { skip, isWindows, isIBMi } = require('../common');
const { throws } = require('assert');
const { isMainThread } = require('worker_threads');

if (!isMainThread) {
  skip('process.execve is not available in Workers');
}

if (!isWindows && !isIBMi) {
  // Invalid path name
  {
    throws(() => {
      process.execve(123);
    }, {
      name: 'TypeError',
      code: 'ERR_INVALID_ARG_TYPE',
      message: 'The "execPath" argument must be of type string. Received type number (123)'
    });
  }

  // Invalid args
  {
    throws(() => {
      process.execve(process.execPath, '123');
    }, {
      name: 'TypeError',
      code: 'ERR_INVALID_ARG_TYPE',
      message: `The "args" argument must be an instance of Array. Received type string ('123')`
    });

    throws(() => {
      process.execve(process.execPath, [123]);
    }, {
      name: 'TypeError',
      code: 'ERR_INVALID_ARG_VALUE',
      message: "The argument 'args[0]' must be a string without null bytes. Received 123",
    });

    throws(() => {
      process.execve(process.execPath, ['123', 'abc\u0000cde']);
    }, {
      name: 'TypeError',
      code: 'ERR_INVALID_ARG_VALUE',
      message: "The argument 'args[1]' must be a string without null bytes. Received 'abc\\x00cde'",
    });
  }

  // Invalid env
  {
    throws(() => {
      process.execve(process.execPath, [], '123');
    }, {
      name: 'TypeError',
      code: 'ERR_INVALID_ARG_TYPE',
      message: `The "env" argument must be of type object. Received type string ('123')`
    });

    throws(() => {
      process.execve(process.execPath, [], { abc: 123 });
    }, {
      name: 'TypeError',
      code: 'ERR_INVALID_ARG_VALUE',
      message:
        "The argument 'env' must be an object with string keys and values without null bytes. Received { abc: 123 }"
    });

    throws(() => {
      process.execve(process.execPath, [], { abc: '123', cde: 'abc\u0000cde' });
    }, {
      name: 'TypeError',
      code: 'ERR_INVALID_ARG_VALUE',
      message:
        "The argument 'env' must be an object with string keys and values without null bytes. " +
        "Received { abc: '123', cde: 'abc\\x00cde' }",
    });
  }
} else {
  throws(() => {
    process.execve(
      process.execPath,
      [__filename, 'replaced'],
      { ...process.env, EXECVE_A: 'FIRST', EXECVE_B: 'SECOND', CWD: process.cwd() }
    );
  }, { name: 'TypeError', code: 'ERR_FEATURE_UNAVAILABLE_ON_PLATFORM' });
}
