import test from 'node:test';
import assert from 'node:assert/strict';
import { EventEmitter } from 'node:events';

import { CertificationService } from './CertificationService.js';

function createSave(initialState) {
  let state = structuredClone(initialState);
  return {
    get() {
      return state;
    },
    set(partial) {
      state = {
        ...state,
        ...partial
      };
      return state;
    }
  };
}

test('CertificationService awards workstation foundations once prerequisite quests are complete', () => {
  const bus = new EventEmitter();
  const sent = [];
  const save = createSave({ certifications: [] });
  const completed = new Set();

  const service = new CertificationService({
    bus,
    save,
    quests: {
      isCompleted(questId) {
        return completed.has(questId);
      }
    },
    email: {
      send(payload) {
        sent.push(payload);
        return payload;
      }
    }
  });

  service.initialize(save.get());
  assert.equal(save.get().certifications.length, 0);

  completed.add('Q001');
  bus.emit('quest:completed', { questId: 'Q001' });
  assert.equal(save.get().certifications.length, 0);

  completed.add('Q002');
  bus.emit('quest:completed', { questId: 'Q002' });

  assert.equal(save.get().certifications.length, 1);
  assert.equal(save.get().certifications[0].id, 'workstation-foundations');
  assert.equal(sent.length, 1);

  bus.emit('quest:completed', { questId: 'Q002' });
  assert.equal(save.get().certifications.length, 1);
  assert.equal(sent.length, 1);
});
