import { useGetProductsDetail, useGetProductsVariationsList } from '~/api/queries/wp' export const useProduct = (variantId) => { const route = useRoute() const currentId = ref(route.params.id ?? variantId) const { data: productsData } = useGetProductsDetail(currentId) const { data: productsVariationsData } = useGetProductsVariationsList(currentId) function getAttribute(attributes: string[], name: string) { return attributes?.find(attribute => attribute?.name === name) } const defaultColor = computed(() => getAttribute(productsData?.value?.default_attributes, 'color')?.option) const defaultMaterial = computed(() => getAttribute(productsData?.value?.default_attributes, 'material')?.option) const defaultSize = computed(() => getAttribute(productsData?.value?.default_attributes, 'size')?.option) const defaultVariant = computed(() => { return productsVariationsData?.value?.find(variation => getAttribute(variation?.attributes, 'color')?.option === defaultColor?.value) && productsVariationsData?.value?.find(variation => getAttribute(variation?.attributes, 'material')?.option === defaultMaterial?.value) }) const colors = computed(() => getAttribute(productsData?.value?.attributes, 'color')?.options) const materials = computed(() => getAttribute(productsData?.value?.attributes, 'material')?.options) const sizes = computed(() => getAttribute(productsData?.value?.attributes, 'size')?.options) const color = computed(() => getAttribute(productsData?.value?.attributes, 'color')?.option) const material = computed(() => getAttribute(productsData?.value?.attributes, 'material')?.option) const size = computed(() => getAttribute(productsData?.value?.attributes, 'size')?.option) function getIdentifier(productVariant) { const color = getAttribute(productVariant?.attributes, 'color')?.option const material = getAttribute(productVariant?.attributes, 'material')?.option return `${color}_${material}` } const variations = computed(() => colors?.value?.map((color) => { if (!productsVariationsData?.value) { return [] } const productAsColor = productsVariationsData?.value?.filter(variant => getAttribute(variant?.attributes, 'color')?.option === color) const identifier = getIdentifier(productAsColor[0]) return { identifier, image: productsData?.value?.images?.filter(img => img?.src?.includes(`${identifier}_`)), options: productAsColor, } }) ?? []) return { productsData, productsVariationsData, defaultColor, defaultMaterial, defaultSize, defaultVariant, colors, materials, sizes, color, material, size, variations, getAttribute, getIdentifier, } }