/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

/**
 * Tests telemetry is captured when search service initialization has failed or
 * succeeded.
 */

add_setup(async () => {
  consoleAllowList.push("#init: failure initializing search:");
  SearchTestUtils.setRemoteSettingsConfig([{ identifier: "unused" }]);
  Services.fog.initializeFOG();
});

add_task(async function test_init_success_telemetry() {
  Assert.equal(
    SearchService.isInitialized,
    false,
    "Search Service should not be initialized."
  );

  await SearchService.init();

  Assert.equal(
    SearchService.hasSuccessfullyInitialized,
    true,
    "Search Service should have initialized successfully."
  );

  Assert.equal(
    1,
    await Glean.searchService.initializationStatus.success.testGetValue(),
    "Should have incremented init success by one."
  );
});

add_task(async function test_init_failure_telemetry() {
  await startInitFailure("Settings");
  Assert.equal(
    1,
    await Glean.searchService.initializationStatus.failedSettings.testGetValue(),
    "Should have incremented get settings failure by one."
  );

  await startInitFailure("FetchEngines");
  Assert.equal(
    1,
    await Glean.searchService.initializationStatus.failedFetchEngines.testGetValue(),
    "Should have incremented fetch engines failure by one."
  );

  await startInitFailure("LoadEngines");
  Assert.equal(
    1,
    await Glean.searchService.initializationStatus.failedLoadEngines.testGetValue(),
    "Should have incremented load engines failure by one."
  );

  // This error is recognized based on the error message, so we set it explicitly.
  await startInitFailure("LoadSettingsAddonManager", "Addon manager failed");
  Assert.equal(
    1,
    await Glean.searchService.initializationStatus.failedLoadSettingsAddonManager.testGetValue(),
    "Should have incremented get settings addon manager failure by one."
  );

  // This type of failure should not be reported in telemetry.
  await startInitFailure(
    "LoadSettingsAddonManager",
    "Addon manager shutting down"
  );
  Assert.equal(
    1,
    await Glean.searchService.initializationStatus.failedLoadSettingsAddonManager.testGetValue(),
    "Should not have incremented load get settings addon manager failure."
  );
});

add_task(async function test_corrupt_settings() {
  consoleAllowList.push("get: Settings file empty or corrupt.");
  SearchService.reset();

  // Prevent `SearchUIUtils.searchSettingsResetNotificationBox` from
  // running because it would fail since there is no window.
  let notificationBoxStub = sinon.stub(
    SearchService,
    "_showSearchSettingsResetNotificationBox"
  );

  await IOUtils.writeJSON(
    PathUtils.join(PathUtils.profileDir, SETTINGS_FILENAME),
    "{invalid json",
    { compress: true }
  );

  Assert.equal(
    SearchService.isInitialized,
    false,
    "Search Service should not be initialized."
  );
  await SearchService.init();
  Assert.equal(
    SearchService.hasSuccessfullyInitialized,
    true,
    "Search Service should have initialized successfully."
  );

  Assert.equal(
    1,
    await Glean.searchService.initializationStatus.settingsCorrupt.testGetValue(),
    "Should have incremented settings corrupt by one."
  );
  notificationBoxStub.reset();
});

async function startInitFailure(errorType, errorMessage) {
  SearchService.reset();
  SearchService.errorToThrowInTest.type = errorType;
  SearchService.errorToThrowInTest.message = errorMessage;

  Assert.equal(
    SearchService.isInitialized,
    false,
    "Search Service should not be initialized."
  );

  let messageRegex = new RegExp(
    errorMessage ??
      `Fake ${errorType} error during search service initialization.`
  );

  await Assert.rejects(
    SearchService.init(),
    messageRegex,
    "Should have thrown an error on init."
  );

  await Assert.rejects(
    SearchService.promiseInitialized,
    messageRegex,
    "Should have rejected the promise."
  );

  SearchService.errorToThrowInTest = { type: null, message: null };
}
