import test from "node:test";
import assert from "node:assert/strict";
import { createSystemNotificationAdapter, deliverSystemNotifications } from "./system-notification.js";
import { DEFAULT_NOTIFICATION_PREFERENCES } from "./notification-settings.js";

test("system delivery only shows newly added, allowed notifications after permission", async () => {
  const shown = [];
  const adapter = {
    permission: async () => "granted",
    show: async (notification) => shown.push(notification.id)
  };
  const previous = [{ id: "old", type: "approval" }];
  const next = [
    { id: "new-optional", type: "weekly-reset" },
    { id: "new-important", type: "completed" },
    ...previous
  ];
  await deliverSystemNotifications(previous, next, DEFAULT_NOTIFICATION_PREFERENCES, adapter);
  assert.deepEqual(shown, ["new-important"]);
});

test("system delivery never prompts for permission by itself", async () => {
  let shown = false;
  const adapter = { permission: async () => "prompt", show: async () => { shown = true; } };
  await deliverSystemNotifications([], [{ id: "approval", type: "approval" }], DEFAULT_NOTIFICATION_PREFERENCES, adapter);
  assert.equal(shown, false);
});

test("system notification uses the chat title without changing the existing body", async () => {
  const shown = [];
  const OriginalNotification = globalThis.Notification;
  globalThis.Notification = class {
    constructor(title, options) {
      shown.push({ title, body: options.body });
    }
  };

  try {
    const adapter = createSystemNotificationAdapter();
    await adapter.show({
      id: "completed:session-1",
      title: "Response complete",
      detail: "Existing body",
      conversationTitle: "Actual chat title",
      sessionId: "session-1"
    });
  } finally {
    globalThis.Notification = OriginalNotification;
  }

  assert.deepEqual(shown, [{ title: "Actual chat title", body: "Existing body" }]);
});
