import { atom } from 'jotai';
import { UserEvent } from 'src/application/models';

const internalUserEventQueueAtom = atom<UserEvent[]>([]);

export const userEventQueueAtom = atom(get => {
  const queue = get(internalUserEventQueueAtom);
  return queue === undefined ? [] : queue.filter(v => v !== undefined);
});

/**
 * This atom is used to queue a new message for processing on `next_responses`
 * It receives a single `userEvent` that is added to the processing queue.
 * If the event has the same eventId as an existing message in the queue the NEW
 * event is ignored
 */
export const queueUserEventAtom = atom(null, (get, set, userEvent: UserEvent) => {
  if (userEvent === undefined) {
    return;
  }
  set(internalUserEventQueueAtom, [...get(internalUserEventQueueAtom), userEvent]);
});

/**
 * This atom exposes a function to reset the entire queue. All messages in the queue will be purged
 */
export const clearUserEventAtom = atom(null, (_, set) => {
  set(internalUserEventQueueAtom, []);
});

/**
 * This atom is used to mark events as processed and remove them from the queue
 * It accepts a list of eventId values and will remove all events with those eventIds from the queue.
 */
export const processUserEventAtom = atom(null, (get, set, eventIds: string[]) => {
  const curr = get(internalUserEventQueueAtom);
  const remaining = curr?.filter(event => !eventIds.includes(event.eventId));
  set(internalUserEventQueueAtom, remaining);
});

export const userQueueEventCountAtom = atom(get => get(userEventQueueAtom).length); // Import necessary enums
// import type { Context } from "@spiffy-ai/commerce-api-client/dist/models/Context"; // Import Context type
