'use strict';

/**
 * Unit tests for the service worker's activate handler (Task #55).
 *
 * Bug: "Update ready / Reload now" got stuck in a loop. Root cause —
 * activate() unconditionally broadcast SW_UPDATE_AVAILABLE to every open
 * client, even when this activation was just the first-ever install of a
 * freshly (re)registered worker (e.g. right after the "Refresh UI" button's
 * hardReloadUI() wipes every cache, unregisters the SW, and hard-navigates).
 * That harmless re-install re-announced "update available" and immediately
 * reopened the banner the user had just dismissed.
 *
 * sw.js runs in a ServiceWorkerGlobalScope, which Node doesn't provide, so
 * these tests load the real source into a minimal vm sandbox that mocks
 * `self`, `caches`, and `self.clients`, then drive the registered
 * `activate` listener directly.
 */

const { test } = require('node:test');
const assert = require('node:assert');
const vm = require('node:vm');
const fs = require('node:fs');
const path = require('node:path');

const SW_SOURCE = fs.readFileSync(path.join(__dirname, 'sw.js'), 'utf8');

// Builds a fresh sandboxed SW environment with the given starting cache keys
// and returns handles to drive/inspect it.
function loadSw(initialCacheKeys) {
  const cacheStore = new Set(initialCacheKeys);
  const deleted = [];
  const clientMessages = [];

  const listeners = {};
  const self_ = {
    addEventListener(type, fn) {
      (listeners[type] = listeners[type] || []).push(fn);
    },
    clients: {
      async claim() {},
      async matchAll() {
        return [{ postMessage: (msg) => clientMessages.push(msg) }];
      },
    },
  };

  const caches_ = {
    async keys() { return Array.from(cacheStore); },
    async delete(key) { deleted.push(key); return cacheStore.delete(key); },
    async open(key) {
      cacheStore.add(key);
      return { addAll: async () => {}, match: async () => undefined, put: async () => {} };
    },
  };

  const sandbox = {
    self: self_,
    caches: caches_,
    fetch: async () => { throw new Error('fetch not mocked'); },
    Response: class { constructor(body, init) { this.body = body; Object.assign(this, init); } },
    URL,
    console,
  };
  vm.createContext(sandbox);
  vm.runInContext(SW_SOURCE, sandbox, { filename: 'sw.js' });

  async function triggerActivate() {
    let waitPromise = Promise.resolve();
    const event = { waitUntil: (p) => { waitPromise = p; } };
    for (const fn of listeners.activate || []) fn(event);
    await waitPromise;
  }

  return { triggerActivate, deleted, clientMessages, cacheStoreRemaining: () => Array.from(cacheStore) };
}

test('activate does NOT broadcast on a fresh install (only the current-version cache exists)', async () => {
  const sw = loadSw(['ytplayer-v1.0.4']); // default VERSION fallback in sw.js is 'v1.0.4'
  await sw.triggerActivate();

  assert.deepStrictEqual(sw.clientMessages, [], 'no update banner should be triggered on first-ever install');
  assert.deepStrictEqual(sw.deleted, [], 'nothing stale to evict on a fresh install');
});

test('activate DOES broadcast when an older versioned shell cache is present (genuine update)', async () => {
  const sw = loadSw(['ytplayer-v1.0.4', 'ytplayer-v1.0.2']);
  await sw.triggerActivate();

  assert.strictEqual(sw.clientMessages.length, 1, 'a genuine version bump should notify clients once');
  assert.strictEqual(sw.clientMessages[0].type, 'SW_UPDATE_AVAILABLE');
  assert.deepStrictEqual(sw.deleted, ['ytplayer-v1.0.2'], 'the stale shell cache should be evicted');
});

test('activate never deletes the utility caches (thumbs/fonts), broadcast or not', async () => {
  const sw = loadSw(['ytplayer-v1.0.4', 'ytplayer-thumbs', 'ytplayer-fonts']);
  await sw.triggerActivate();

  assert.deepStrictEqual(sw.clientMessages, [], 'utility caches alone are not a version bump');
  assert.deepStrictEqual(sw.deleted, [], 'utility caches must survive activate');
  assert.deepStrictEqual(
    sw.cacheStoreRemaining().sort(),
    ['ytplayer-fonts', 'ytplayer-thumbs', 'ytplayer-v1.0.4'].sort()
  );
});

test('activate reports an update and still preserves utility caches together', async () => {
  const sw = loadSw(['ytplayer-v1.0.4', 'ytplayer-v1.0.2', 'ytplayer-thumbs', 'ytplayer-fonts']);
  await sw.triggerActivate();

  assert.strictEqual(sw.clientMessages.length, 1);
  assert.deepStrictEqual(sw.deleted, ['ytplayer-v1.0.2']);
  assert.deepStrictEqual(
    sw.cacheStoreRemaining().sort(),
    ['ytplayer-fonts', 'ytplayer-thumbs', 'ytplayer-v1.0.4'].sort()
  );
});
