import {
    PrintfulClient,
    ProductSyncer,
    WebflowClient,
} from "@blade-and-brawn/commerce";
import { env } from "../util";

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

type Validation = {
    isValid: boolean;
    message: string;
};

const validateEquality = (wValue: any, pValue: any): Validation => {
    const validation = {
        isValid: true,
        message: "Valid",
    };

    if (wValue !== pValue) {
        validation.isValid = false;
        validation.message = `${wValue} !== ${pValue}`;
    }

    return validation;
};

const printful = new PrintfulClient({
    token: env.PRINTFUL_AUTH,
    storeId: env.PRINTFUL_STORE_ID,
});

const webflow = new WebflowClient({
    siteId: env.WEBFLOW_SITE_ID,
    collectionIds: {
        products: env.WEBFLOW_COLLECTION_PRODUCTS_ID,
        skus: env.WEBFLOW_COLLECTION_SKUS_ID
    },
    token: env.WEBFLOW_AUTH,
    webhookSecret: env.WEBFLOW_WEBHOOK_SECRET,
});

const syncer = new ProductSyncer(printful, webflow);

const wProducts = await webflow.Products.list({ forceAll: true });

let invalidCount = 0;
for (const wProduct of wProducts) {
    for (const wSku of wProduct.skus ?? []) {
        console.log("Webflow: " + wSku.id, wSku.fieldData.name);

        const pVariant = await printful.Products.Variants.get(`@${wSku.id}`);
        if (pVariant) {
            console.log("Printful: " + pVariant.id, pVariant.name);
            const expectedColor = syncer.parseColorGroup(pVariant.name) ?? pVariant.color;
            const validations = [
                // validateEquality(sku.fieldData.name, pVariant.name),
                validateEquality(
                    wSku.fieldData["sku-values"]?.["color"],
                    expectedColor,
                ),
                validateEquality(
                    wSku.fieldData["sku-values"]?.["size"],
                    pVariant.size,
                ),
                validateEquality(
                    wSku.fieldData.price.value,
                    Math.round(+pVariant.retail_price * 100),
                ),
            ];

            // if (!validateEquality(sku.fieldData.name, pVariant.name).isValid) {
            //     sku.fieldData.name = pVariant.name;
            //     await webflow.Products.Skus.update(wProduct.product.id, sku.id, sku);
            // }

            const errors = validations.filter((v) => !v.isValid);
            if (errors.length) {
                ++invalidCount;
                console.log("INVALID: ");
                console.log(errors.map((e) => e.message).join(", "));
            } else {
                console.log("VALID");
            }
        } else {
            ++invalidCount;
            console.log("INVALID");
            console.log("Not found");
        }
        console.log();
    }
    await sleep(3000);
}

console.log("INVALID COUNT: " + invalidCount);
