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

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

// Create a cart
const createCart = async () => {
  const query = `
    mutation CreateCart {
      cartCreate {
        cart {
          id
          createdAt
          updatedAt
        }
      }
    }
  `;
  const { data } = await client.request(query);
  return data.cartCreate.cart;
};

// Add a line item to the cart
const addItemToCart = async (cartId, lines) => {

  const query = `
    mutation($cartId: ID!, $lines: [CartLineInput!]!) {
      cartLinesAdd(cartId: $cartId, lines: $lines) {
        cart {
          id
          checkoutUrl
          createdAt
          updatedAt
          cost {
            totalAmount {
              amount
              currencyCode
            }
            subtotalAmount {
              amount
              currencyCode
            }
            totalTaxAmount {
              amount
              currencyCode
            }
          }
          lines(first: 99) {
            nodes {
              id
              merchandise {
                ... on ProductVariant {
                  id
                  title
                  product {
                    id
                  }
                  selectedOptions {
                    name
                    value
                  }
                  image {
                    src
                  }
                  product {
                    title
                    collections(first: 5) {
                      nodes {
                        title
                      }
                    }
                  }
                }
              }
              quantity
              cost {
                totalAmount {
                  amount
                  currencyCode
                }
              }
            }
          }
        }
      }
    }
  `;
  const variables = { cartId, lines };

  const {data, errors, extensions} = await client.request(query,{
    variables: {
      cartId,
      lines
    }
  });
  
  return data.cartLinesAdd.cart;
};

// Get cart details
const getCart = async (cartId) => {

  const query = `
    {
      cart(id: "${cartId}") {
        id
        checkoutUrl
        createdAt
        updatedAt
        cost {
          totalAmount {
            amount
            currencyCode
          }
          subtotalAmount {
            amount
            currencyCode
          }
          totalTaxAmount {
            amount
            currencyCode
          }
        }
        lines(first: 10) {
          nodes {
            id
            merchandise {
              ... on ProductVariant {
                id
                title
                product {
                  id
                }
                selectedOptions {
                  name
                  value
                }
                image {
                  src
                }
                product {
                  title
                  collections(first: 5) {
                    nodes {
                      title
                    }
                  }
                }
              }
            }
            quantity
            cost {
              totalAmount {
                amount
                currencyCode
              }
            }
          }
        }
      }
        
    }
  `;

  const { data } = await client.request(query);
  return data.cart;
};


// Update a line item's quantity
const updateItemQuantity = async (cartId, lineId, quantity) => {

  
  const query = `
    mutation UpdateItemQuantity($cartId: ID!, $lines: [CartLineUpdateInput!]!) {
      cartLinesUpdate(cartId: $cartId, lines: $lines) {
        cart {
          id
          checkoutUrl
          createdAt
          updatedAt
          cost {
            totalAmount {
              amount
              currencyCode
            }
            subtotalAmount {
              amount
              currencyCode
            }
            totalTaxAmount {
              amount
              currencyCode
            }
          }
          lines(first: 99) {
            nodes {
              id
              merchandise {
                ... on ProductVariant {
                  id
                  title
                  product {
                    id
                  }
                  selectedOptions {
                    name
                    value
                  }
                  image {
                    src
                  }
                  product {
                    title
                    collections(first: 5) {
                      nodes {
                        title
                      }
                    }
                  }
                }
              }
              quantity
              cost {
                totalAmount {
                  amount
                  currencyCode
                }
              }
            }
          }
        }
      }
    }
  `;
  const variables = {
    cartId,
    lines: [{ id: lineId, quantity }],
  };
  const {data, errors, extensions} = await client.request(query,{
    variables: {
      cartId,
      lines: [{ id: lineId, quantity }]
    }
  });
  return data.cartLinesUpdate.cart;
};

// Generate checkout URL
const getCheckoutUrl = async (cartId) => {
  const query = `
    query CheckoutURL($cartId: ID!) {
      cart(id: $cartId) {
        checkoutUrl
      }
    }
  `;
  const variables = { cartId };
  const { data } = await client.request(query, variables);
  return data.cart.checkoutUrl;
};

// Export services
const CartService = {
  createCart,
  addItemToCart,
  getCart,
  updateItemQuantity,
  getCheckoutUrl,
};

export default CartService;
