import { Message, MessageRole, MessageType } from 'src/application/models/message';
import { UserEvent } from 'src/application/models';

/**
 * Searches the chat history for the form message by form response ID and builds the display string for the form.
 */
export const buildFormSubmittedDisplayContent = (
  messages: Message[][],
  formResponseId: string,
  filledSchema: Record<string, unknown>,
): string => {
  let formFields: { key: string; title: string }[] = [];
  // Find the form message in the chat history
  for (const turn of messages) {
    for (const msg of turn) {
      if (
        msg.type === MessageType.Form &&
        msg.id === formResponseId &&
        msg.metadata &&
        'fields' in msg.metadata &&
        Array.isArray(msg.metadata.fields)
      ) {
        formFields = msg.metadata.fields.map((field: { key: string; title: string }) => ({
          key: field.key,
          title: field.title,
        }));
        break;
      }
    }
    if (formFields.length > 0) break;
  }
  // Build the display string for the form
  const formStringContent =
    formFields.length > 0
      ? formFields.map(({ key, title }) => `${title}: ${filledSchema[key] ?? ''}`).join('\n')
      : Object.entries(filledSchema)
          .map(([key, value]) => `${key}: ${value}`)
          .join('\n');
  return formStringContent;
};

/**
 * Creates a user message representing a submitted form for display in the chat.
 */
export const createFormSubmittedUserMessage = (
  userEvent: UserEvent,
  formSubmittedContent: string,
): Message => {
  const newMessage: Message = {
    id: userEvent.eventId,
    role: MessageRole.User,
    type: MessageType.QueryTyped,
    createdAt: userEvent.createdAt,
    metadata: { content: formSubmittedContent },
  };
  return newMessage;
};
