import { notFound, ok, serverError } from 'wix-http-functions';
import wixData from 'wix-data';
import wixStores from 'wix-stores-backend';

const imageAccesible = image =>`https://static.wixstatic.com/media/${image}`;

export async function get_productsListing() {
    const options = {
        headers: {
            'Content-Type': 'application/json',
        },
    };
    try {
        const result = await wixData.query('Stores/Products')
            .include('inventoryItem', 'variant')
            // .limit(1000)
            .find();
        if (result.items.length > 0) {
            for (let i = 0; i < result.items.length; i += 1) {
                const product = result.items[i];
                const media = product.mediaItems;
                for (let j = 0; j < media.length; j += 1) {
                    media[j].id = imageAccesible(media[j].id);
                }
                if (media && media[0]) {
                    product.mediaItems = media[0].id;
                }
                // Fetch the variants
                /* eslint no-underscore-dangle: 0 */
                const variants = await wixStores.getProductVariants(product._id, {});
                product.mappedVariants = variants;
            }
            options.body = {
                items: result.items,
            };
            return ok(options);
        }
        options.body = {
            error: 'Result not found!',
        };
        return notFound(options);
    } catch (onRejected) {
        options.body = {
            error: onRejected.message,
        };
        return serverError(options);
    }
}