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

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

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

test('ShiftReviewService tracks ticket activity and generates a review email on shift end', () => {
  const bus = new EventEmitter();
  const sent = [];
  const save = createSave({
    shift_number: 1,
    shift_started_at: '2026-04-25T12:00:00.000Z',
    current_shift_stats: {
      assigned_ticket_ids: [],
      resolved_tickets: [],
      flagged_issues: []
    },
    shift_history: []
  });

  const service = new ShiftReviewService({
    bus,
    save,
    email: {
      send(payload) {
        sent.push(payload);
        return payload;
      }
    },
    tickets: {
      getAll() {
        return [];
      }
    },
    loader: {
      get(type, id) {
        if (type === 'dialogue' && id === 'priya-shift-review') {
          return {
            messages: [
              { stage: 'excellent', body: 'Strong shift.' },
              { stage: 'ok', body: 'Acceptable shift.' },
              { stage: 'poor', body: 'This shift needs review.' }
            ]
          };
        }

        return null;
      }
    },
    now: () => new Date('2026-04-25T12:30:00.000Z').getTime()
  });

  service.initialize(save.get());

  bus.emit('ticket:activated', { ticketId: 'T001' });
  bus.emit('ticket:completed', {
    ticketId: 'T001',
    branchId: 'correct-setup',
    trustDelta: 1,
    activatedAt: '2026-04-25T12:05:00.000Z',
    resolvedAt: '2026-04-25T12:15:00.000Z'
  });
  bus.emit('shift:ended', { startedAt: '2026-04-25T12:00:00.000Z', remainingSeconds: 0 });

  const state = save.get();
  assert.equal(state.shift_number, 2);
  assert.equal(state.shift_history.length, 1);
  assert.equal(state.shift_history[0].tickets_resolved, 1);
  assert.equal(state.shift_history[0].tickets_assigned, 1);
  assert.equal(state.shift_history[0].performance_tier, 'excellent');
  assert.equal(sent.length, 1);
  assert.match(sent[0].subject, /Shift 1 review/);
});
