import {
  NavigationGroup,
  NavigationGroupItem,
  SpaceProperties
} from 'storefrontSdkV1';
import { NavigationGroup as NavigationGroupV2 } from '@nacelle/commerce-queries-plugin';
import { Link, Maybe, Metafield, NacelleShopSpace } from '@nacelle/types';

type NavigationGroupItemsV2 = NonNullable<NavigationGroupV2['items']>;

// This is a convenience type to sort of merge the disparate SpaceData between Warp2 & Warp1
export type CompatibilitySpace = {
  spaceProperties: Maybe<SpaceProperties>;
  navigation: Maybe<NavigationGroup[] | NavigationGroupV2[]>;
  spaceId: string;
};

function transformLinks(
  items: NavigationGroupItem[] | NavigationGroupItemsV2
): Link[] {
  return items.map((item) => ({
    title: item.title,
    to: item.url,
    type: item.type && item.type.charAt(0) + item.type.toLowerCase().slice(1),
    links: item?.items?.length ? transformLinks(item.items) : null
  }));
}

export function transformSpace(space: CompatibilitySpace): NacelleShopSpace {
  const metafields: Maybe<Metafield[]> =
    space.spaceProperties?.properties
      ?.map((property) => {
        const namespace = property?.namespace ?? '';
        return (
          property?.items?.map((item) => ({
            key: item?.key ?? '',
            value: item?.value ?? '',
            namespace
          })) ?? []
        );
      })
      .flat() ?? [];
  const linklists = space.navigation?.map((group) => {
    return {
      handle: group.groupId,
      links: group?.items?.length ? transformLinks(group.items) : null
    };
  });

  return {
    id: space.spaceId, // required by type
    name: '',
    domain: '',
    linklists,
    metafields,
    pimSyncSourceDomain: '', // required by type
    cmsSyncSourceDomain: ''
  };
}
