import { UrlResolverResponse } from 'src/atoms/app/variant';
import {
  UserEvent as ApiUserEvent,
  PageVisitCategory,
  UserEventCategory,
} from '@spiffy-ai/commerce-api-client';
import { UserEvent, VariantTypeEnum } from 'src/application/models';
import { isApiPDPAttributes } from 'src/application/models/guards/api/isApiPDPEventAttributes';
import {
  isApiPLPEventAttributes,
  isApiPLPIdAttribute,
} from 'src/application/models/guards/api/isApiPLPEventAttributes';
import { isApiQueryTypedAttributes } from 'src/application/models/guards/api/isApiQueryTypedEventAttributes';
import { isApiSearchAttributes } from 'src/application/models/guards/api/isApiSearchEventAttributes';
import { isApiSuggestionClickedAttributes } from 'src/application/models/guards/api/isApiSuggestionClickedEventAttributes';
import { isApiFormSubmittedResponseAttributes } from 'src/application/models/guards/api/isApiFormSubmittedResponseAttributes';

import {
  FullPageSalesAgentVariantInfo,
  HomeVariantInfo,
  OtherVariantInfo,
  PageVariantInfo,
  VisitPageVariantInfo,
} from './types';

export const mapUrlResolverResponseToVariantInfo = (
  url: string,
  response: UrlResolverResponse,
): PageVariantInfo => {
  if (
    response.variant_type === VariantTypeEnum.Pdp &&
    'pdp_attributes' in response.specific_details
  ) {
    return {
      variantType: VariantTypeEnum.Pdp,
      productId: response.specific_details.pdp_attributes.product_id ?? '',
      collections: response.specific_details.collections ?? [],
      numberOfReviews: response.specific_details.number_of_reviews ?? 0,
      merchantTags: response.specific_details.merchant_tags ?? [],
      url,
    };
  }
  if (
    response.variant_type === VariantTypeEnum.Plp &&
    'plp_attributes' in response.specific_details
  ) {
    return {
      variantType: VariantTypeEnum.Plp,
      plpId: response.specific_details.plp_attributes?.attributes?.id ?? '',
      topCategory: response.specific_details.top_category ?? '',
      url,
    };
  }
  if (response.variant_type === VariantTypeEnum.PageVisit) {
    return {
      variantType: VariantTypeEnum.PageVisit,
      url,
    } as VisitPageVariantInfo;
  }

  if (response.variant_type === VariantTypeEnum.Home) {
    return {
      variantType: VariantTypeEnum.Home,
      url,
    } as HomeVariantInfo;
  }

  if (response.variant_type === VariantTypeEnum.Other) {
    return {
      variantType: VariantTypeEnum.Other,
      url,
    } as OtherVariantInfo;
  }

  if (response.variant_type === VariantTypeEnum.FullPageSalesAgent) {
    return {
      variantType: VariantTypeEnum.FullPageSalesAgent,
      url,
    } as FullPageSalesAgentVariantInfo;
  }
  throw new Error('Invalid variant type');
};

const isApiPageVisitAttributes = (
  data: unknown,
): data is { url: string; page_visit_category: PageVisitCategory } => {
  if (data == null || typeof data !== 'object') {
    return false;
  }

  if (!('url' in data) || typeof data.url !== 'string') {
    return false;
  }

  if (
    !('page_visit_category' in data) ||
    typeof data.page_visit_category !== 'string' ||
    !Object.values(PageVisitCategory).includes(data.page_visit_category as PageVisitCategory)
  ) {
    return false;
  }

  return true;
};

export const mapApiUserEventToUserEvent = (
  userEvent: ApiUserEvent | undefined,
): UserEvent | undefined => {
  if (!userEvent) {
    return undefined;
  }
  // Handle PdpVisit and AddToCart (they share the same attributes structure)
  if (
    (userEvent.category === UserEventCategory.PdpVisit ||
      userEvent.category === UserEventCategory.AddToCart) &&
    isApiPDPAttributes(userEvent.attributes)
  ) {
    return {
      eventId: userEvent.event_id,
      createdAt: userEvent.created_at,
      category: userEvent.category,
      attributes: {
        productId: userEvent.attributes.product_id,
        parentProductId:
          userEvent.attributes.parent_product_id !== null
            ? userEvent.attributes.parent_product_id
            : '',
        url: userEvent.attributes.url,
      },
    };
  }

  // Handle PlpVisit
  if (
    userEvent.category === UserEventCategory.PlpVisit &&
    isApiPLPEventAttributes(userEvent.attributes)
  ) {
    if (isApiPLPIdAttribute(userEvent.attributes.attributes)) {
      return {
        eventId: userEvent.event_id,
        createdAt: userEvent.created_at,
        category: UserEventCategory.PlpVisit,
        attributes: {
          category: userEvent.attributes.category,
          attributes: {
            id: userEvent.attributes.attributes.id,
          },
        },
      };
    }
  }

  // Handle QueryTyped
  if (
    userEvent.category === UserEventCategory.QueryTyped &&
    isApiQueryTypedAttributes(userEvent.attributes)
  ) {
    return {
      eventId: userEvent.event_id,
      createdAt: userEvent.created_at,
      category: UserEventCategory.QueryTyped,
      attributes: {
        query: userEvent.attributes.query,
      },
    };
  }

  // Handle Search
  if (
    userEvent.category === UserEventCategory.Search &&
    isApiSearchAttributes(userEvent.attributes)
  ) {
    return {
      eventId: userEvent.event_id,
      createdAt: userEvent.created_at,
      category: UserEventCategory.Search,
      attributes: {
        searchTerm: userEvent.attributes.search_term,
        selectedFilters: userEvent.attributes.selected_filters,
      },
    };
  }

  // Handle SuggestionClicked
  if (
    userEvent.category === UserEventCategory.SuggestionClicked &&
    isApiSuggestionClickedAttributes(userEvent.attributes)
  ) {
    return {
      eventId: userEvent.event_id,
      createdAt: userEvent.created_at,
      category: UserEventCategory.SuggestionClicked,
      attributes: {
        suggestionId: userEvent.attributes.suggestion_id,
      },
    };
  }

  // Handle PageVisit
  if (
    userEvent.category === UserEventCategory.PageVisit &&
    isApiPageVisitAttributes(userEvent.attributes)
  ) {
    return {
      eventId: userEvent.event_id,
      createdAt: userEvent.created_at,
      category: UserEventCategory.PageVisit,
      attributes: {
        url: userEvent.attributes.url,
        pageVisitCategory: userEvent.attributes.page_visit_category,
      },
    };
  }

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

  // Handle AppLoaded (no attributes)
  if (userEvent.category === UserEventCategory.AppLoaded) {
    return {
      eventId: userEvent.event_id,
      createdAt: userEvent.created_at,
      category: UserEventCategory.AppLoaded,
    };
  }

  // Handle AppUnloaded (no attributes)
  if (userEvent.category === UserEventCategory.AppUnloaded) {
    return {
      eventId: userEvent.event_id,
      createdAt: userEvent.created_at,
      category: UserEventCategory.AppUnloaded,
    };
  }

  throw new Error(`Invalid user event category: ${userEvent.category}`);
};
