import {
  UserEvent as ApiUserEvent,
  PLPAttributeCategory,
  PLPIdAttributes,
  UserEventCategory,
} from '@spiffy-ai/commerce-api-client';
import { UserEvent as CoreUserEvent } from '../models';

export const coreUserEventToApiUserEvent = (data: CoreUserEvent): ApiUserEvent => {
  if (
    data.category === UserEventCategory.PdpVisit ||
    data.category === UserEventCategory.AddToCart
  ) {
    return {
      event_id: data.eventId,
      created_at: data.createdAt,
      category: data.category,
      attributes: {
        product_id: data.attributes.productId,
        parent_product_id: data.attributes.parentProductId,
        url: data.attributes.url,
      },
    };
  }

  if (data.category === UserEventCategory.PlpVisit) {
    return {
      event_id: data.eventId,
      created_at: data.createdAt,
      category: data.category,
      attributes: {
        category: PLPAttributeCategory.Id,
        attributes: {
          // we're only handling id attributes for now
          id: (data.attributes.attributes as PLPIdAttributes).id,
        },
      },
    };
  }

  if (data.category === UserEventCategory.QueryTyped) {
    return {
      event_id: data.eventId,
      created_at: data.createdAt,
      category: data.category,
      attributes: {
        query: data.attributes.query,
      },
    };
  }

  if (data.category === UserEventCategory.Search) {
    return {
      event_id: data.eventId,
      created_at: data.createdAt,
      category: data.category,
      attributes: {
        search_term: data.attributes.searchTerm,
        selected_filters: data.attributes.selectedFilters,
      },
    };
  }

  if (data.category === UserEventCategory.SuggestionClicked) {
    return {
      event_id: data.eventId,
      created_at: data.createdAt,
      category: data.category,
      attributes: {
        suggestion_id: data.attributes.suggestionId,
      },
    };
  }

  if (data.category === UserEventCategory.PageVisit) {
    return {
      event_id: data.eventId,
      created_at: data.createdAt,
      category: data.category,
      attributes: {
        url: data.attributes.url,
        page_visit_category: data.attributes.pageVisitCategory,
      },
    };
  }

  if (data.category === UserEventCategory.FormSubmitted) {
    return {
      event_id: data.eventId,
      created_at: data.createdAt,
      category: data.category,
      attributes: {
        filled_schema: { ...data.attributes.filledSchema },
        form_response_id: data.attributes.formResponseId,
        form_type: data.attributes.formType,
      },
    };
  }

  // This is the default app_loaded event, when we start to use app_unloaded we need to handle it here
  return {
    event_id: data.eventId,
    created_at: data.createdAt,
    category: data.category,
  };
};
