import { atom } from 'jotai';
import { Message, MessageRole, MessageType, Suggestion } from 'src/application/models';
import {
  messagesAtom,
  replyEventCategoryAtom,
  suggestionAtom,
  userHasRepliedAtom,
} from 'src/atoms/chat';
import { UserEventCategory } from '@spiffy-ai/commerce-api-client';
import { queueUserEventAtom } from './messageQueue';

export const handleSuggestionAtom = atom(null, (get, set, suggestion: Suggestion) => {
  const newMessage: Message = {
    id: suggestion.id,
    role: MessageRole.User,
    type: MessageType.SuggestionClicked,
    createdAt: new Date().toISOString(),
    metadata: {
      suggestionId: suggestion.id,
      suggestionContent: suggestion.content,
    },
  };

  set(replyEventCategoryAtom, UserEventCategory.SuggestionClicked);
  set(suggestionAtom, suggestion);
  set(messagesAtom, [...get(messagesAtom), [newMessage]]);
  set(userHasRepliedAtom, true);
  set(queueUserEventAtom, {
    eventId: suggestion.id,
    category: UserEventCategory.SuggestionClicked,
    createdAt: newMessage.createdAt,
    attributes: {
      suggestionId: suggestion.id,
    },
  });
});
