import { NacelleCollection } from '@nacelle/types';
import { ProductCollection, Product, ProductEdge } from 'storefrontSdkV1';
import { transformSourceEntryId } from './transformSourceEntryId';
import { transformMedia } from './transformMedia';

export interface ProductConnectionNode {
  node: Product;
}

export type ProductCollectionWithProductConnection = Omit<
  ProductCollection,
  'products'
>;

export type ProductCollectionNode = {
  node: ProductCollectionWithProductConnection;
};

export type ProductCollectionGraphQLResponse = {
  allProductCollections: {
    edges: ProductCollectionNode[];
    pageInfo: {
      hasNextPage: boolean;
      endCursor: string;
    };
  };
};

export function transformCollections(
  collections: ProductCollectionWithProductConnection[],
  locale: string
): NacelleCollection[] {
  return collections.map((collection) => {
    const productHandles: string[] = [];

    if (collection.productConnection.edges) {
      const edges: ProductEdge[] = collection.productConnection.edges;
      edges.forEach((product) => {
        if (product.node.content?.handle) {
          productHandles.push(product.node.content.handle);
        }
      });
    }

    const collectionHandle = collection.content?.handle ?? '';
    const collectionTitle = collection.content?.title ?? '';
    const collectionDescription = collection.content?.description ?? '';
    const featuredMedia = transformMedia(collection.content?.featuredMedia);

    return {
      id: collection.nacelleEntryId,
      handle: collectionHandle,
      locale,
      globalHandle: `${collectionHandle}::${locale}`,
      pimSyncSourceDomain: '', // Not available in Warp 2
      pimSyncSource: '', // Not available in Warp 2
      pimSyncSourceCollectionId: transformSourceEntryId(
        collection.sourceEntryId
      ),
      title: collectionTitle,
      description: collectionDescription,
      featuredMedia,
      productLists: [
        {
          title: 'default', // Not available in Warp 2
          slug: 'default', // Not available in Warp 2
          locale,
          handles: productHandles
        }
      ],
      createdAt: collection.createdAt,
      updatedAt: collection.updatedAt,
      indexedAt: collection.indexedAt as number,
      metafields: collection.metafields
    };
  });
}
