import { UserEventCategory } from '@spiffy-ai/commerce-api-client';
import { createStore } from 'jotai';
import { UserEvent } from 'src/application/models';
import {
  clearUserEventAtom,
  processUserEventAtom,
  queueUserEventAtom,
  userEventQueueAtom,
  userQueueEventCountAtom,
} from 'src/atoms/chat/messageQueue';

const userEvent1 = {
  eventId: '123',
  category: UserEventCategory.AppLoaded,
  createdAt: 'now',
} satisfies UserEvent;
const userEvent2 = {
  eventId: '456',
  category: UserEventCategory.AppLoaded,
  createdAt: 'now',
} satisfies UserEvent;

describe('eventQueue', () => {
  it('should be able to enqueue items and show them in the queue', () => {
    const store = createStore();
    store.set(queueUserEventAtom, userEvent1);
    expect(store.get(userEventQueueAtom)).toEqual([userEvent1]);
    expect(store.get(userQueueEventCountAtom)).toBe(1);
  });
  it('should be able to mark eventQueue items as processed and remove them from the queue', () => {
    const store = createStore();
    store.set(queueUserEventAtom, userEvent1);
    store.set(queueUserEventAtom, userEvent2);
    expect(store.get(userEventQueueAtom)).toEqual([userEvent1, userEvent2]);
    expect(store.get(userQueueEventCountAtom)).toBe(2);
    store.set(processUserEventAtom, ['123']);
    expect(store.get(userEventQueueAtom)).toEqual([userEvent2]);
    expect(store.get(userQueueEventCountAtom)).toBe(1);
  });
  it('should be able to mark non-existent eventQueue items as procesed without an exception being raised', () => {
    const store = createStore();
    store.set(queueUserEventAtom, userEvent1);
    store.set(queueUserEventAtom, userEvent2);
    expect(store.get(userEventQueueAtom)).toEqual([userEvent1, userEvent2]);
    expect(store.get(userQueueEventCountAtom)).toBe(2);
    store.set(processUserEventAtom, ['foo']);
    expect(store.get(userEventQueueAtom)).toEqual([userEvent1, userEvent2]);
    expect(store.get(userQueueEventCountAtom)).toBe(2);
  });
  it('should be able to clear all eventQueue items', () => {
    const store = createStore();
    expect(store.get(userQueueEventCountAtom)).toBe(0);
    store.set(queueUserEventAtom, userEvent1);
    store.set(queueUserEventAtom, userEvent2);
    expect(store.get(userEventQueueAtom)).toEqual([userEvent1, userEvent2]);
    expect(store.get(userQueueEventCountAtom)).toBe(2);
    store.set(clearUserEventAtom);
    expect(store.get(userEventQueueAtom)).toEqual([]);
    expect(store.get(userQueueEventCountAtom)).toBe(0);
  });
});
