import { createStorefrontApiClient } from '@shopify/storefront-api-client';
import { REACT_APP_ACCESS_TOKEN, REACT_APP_SHOP_NAME } from '../utils/httpCommon'
import { formatProductData } from '../utils/helpers'

const client = createStorefrontApiClient({
  storeDomain: `https://${REACT_APP_SHOP_NAME}/api/2024-10/graphql.json`,
  apiVersion: '2024-10',
  publicAccessToken: REACT_APP_ACCESS_TOKEN,
});

const getProducts = async () => {

  let hasNextCursor = true
  let products = []; 
  let cursor = ``

  while (hasNextCursor) {

    const query = `{
      products(first: ${250}, ${cursor},  sortKey: CREATED_AT) {
        nodes {
          id
          handle
          title
          createdAt 
          productType
          tags
          priceRange {
            minVariantPrice {
              amount
              currencyCode
            }
            maxVariantPrice {
              amount
              currencyCode
            }
          }
          compareAtPriceRange {
            maxVariantPrice {
              currencyCode
              amount
            }
            minVariantPrice {
              amount
              currencyCode
            }
          }
          images(first: 4) {
            nodes {
              url
            }
          }
          collections(first: 10) {
            nodes {
              title
              image {
                url
              }
              updatedAt
            }
          }
          variants(first: 200) {
            nodes {
              id
              title
              price {
                amount
                currencyCode
              }
            }
          }
          metafield(key: "selected", namespace: "custom") {
            key
            value
          }
        }
        pageInfo {
          hasNextPage
          hasPreviousPage
          endCursor
          startCursor
        }
      }
    }`

    const { data, errors, extensions } = await client.request(query, {
      variables: {},
    });

    let { pageInfo, nodes } = data?.products

    products = [...products, ...nodes]

    if(pageInfo?.hasNextPage) {
      cursor = `after:"${pageInfo?.endCursor}"`
    }else{
      cursor = ``
      hasNextCursor = false
    }

  }

  products = products.map((product) => formatProductData(product))

  return products

}

const getProduct = async (handle = "") => {

  const query = `{
    product(handle: "${handle}") {
      id
      handle
      title
      createdAt 
      productType
      tags
      descriptionHtml
      priceRange {
        minVariantPrice {
          amount
          currencyCode
        }
        maxVariantPrice {
          amount
          currencyCode
        }
      }
      images(first: 4) {
        nodes {
          url
        }
      }
      collections(first: 10) {
        nodes {
          title
          image {
            url
          }
        }
      }
      variants(first: 200) {
        nodes {
          id
          title
          price {
            amount
            currencyCode
          }
          selectedOptions {
            name
            value
          }
          quantityAvailable
          compareAtPrice {
            currencyCode
            amount
          }
        }
      }
      metafield(key: "selected", namespace: "custom") {
        key
        value
      }
    }
  }`

  const { data, errors, extensions } = await client.request(query, {
    variables: {
    },
  });

  return formatProductData(data.product)

}

const ProductService = {
  getProducts,
  getProduct
}

export default ProductService
