import test from "node:test";
import assert from "node:assert/strict";
import {
  DEFAULT_NOTIFICATION_PREFERENCES,
  notificationPreferenceEnabled,
  readNotificationPreferences,
  writeNotificationPreferences
} from "./notification-settings.js";

function memoryStorage(initial = {}) {
  const values = new Map(Object.entries(initial));
  return {
    getItem: (key) => values.get(key) ?? null,
    setItem: (key, value) => values.set(key, value)
  };
}

test("notification preferences default important events on and optional usage updates off", () => {
  assert.equal(DEFAULT_NOTIFICATION_PREFERENCES.enabled, true);
  for (const type of ["approval", "completed", "failed", "interrupted", "usage-exhausted"]) {
    assert.equal(notificationPreferenceEnabled(DEFAULT_NOTIFICATION_PREFERENCES, type), true);
  }
  for (const type of ["usage-low", "usage-critical", "weekly-reset"]) {
    assert.equal(notificationPreferenceEnabled(DEFAULT_NOTIFICATION_PREFERENCES, type), false);
  }
});

test("notification preferences are safely read, sanitized, and persisted", () => {
  const storage = memoryStorage();
  assert.deepEqual(readNotificationPreferences(storage), DEFAULT_NOTIFICATION_PREFERENCES);
  assert.equal(writeNotificationPreferences(storage, { enabled: false, types: { approval: false, missing: true } }), true);
  const saved = readNotificationPreferences(storage);
  assert.equal(saved.enabled, false);
  assert.equal(saved.types.approval, false);
  assert.equal("missing" in saved.types, false);
  assert.equal(saved.types.completed, true);
});

test("the master switch suppresses every system notification", () => {
  assert.equal(notificationPreferenceEnabled({ ...DEFAULT_NOTIFICATION_PREFERENCES, enabled: false }, "approval"), false);
  assert.equal(notificationPreferenceEnabled(DEFAULT_NOTIFICATION_PREFERENCES, "unknown"), false);
});
