import { Printful, PrintfulClient, PrintfulError, Webflow, WebflowClient, WebflowError } from "@blade-and-brawn/commerce";
import { env } from "../util";

const BASE_URL = "http://dev.api.bladeandbrawn.com";

const PRINTFUL_WEBHOOK_URL = `${BASE_URL}/webhook/printful`;
const WEBFLOW_WEBHOOK_URL = `${BASE_URL}/webhook/webflow`;

function printError(err: unknown): never {
    if (err instanceof WebflowError || err instanceof PrintfulError)
        console.error(`${err.message}\n`, JSON.stringify(err.payload, null, 2));
    else
        console.error(err);
    process.exit(1);
}

// Register printful webhook
try {
    console.log("Registering printful webhook...");
    const printful = new PrintfulClient({
        token: env.PRINTFUL_AUTH,
        storeId: env.PRINTFUL_STORE_ID,
    });

    await printful.Webhooks.create(PRINTFUL_WEBHOOK_URL, [
        Printful.Webhook.Event.ProductUpdated,
        Printful.Webhook.Event.ProductDeleted,
        Printful.Webhook.Event.PackageShipped,
    ]);

    const webhook = await printful.Webhooks.get();
    console.log("Finished: ");
    console.log(webhook);
} catch (err) {
    printError(err);
}

// Register webflow webhooks
try {
    console.log("Registering webflow webhooks...");
    const webflow = new WebflowClient({
        siteId: env.WEBFLOW_SITE_ID,
        collectionsId: env.WEBFLOW_COLLECTION_ID,
        token: env.WEBFLOW_AUTH,
        webhookSecret: env.WEBFLOW_WEBHOOK_SECRET,
    });

    const events: Webflow.Webhook.Event[] = [
        Webflow.Webhook.Event.OrderCreated,
    ];

    const webhooksToDelete = await webflow.Webhooks.list({ forceAll: true });
    for (const webhook of webhooksToDelete)
        await webflow.Webhooks.remove(webhook.id);

    for (const event of events)
        await webflow.Webhooks.create(WEBFLOW_WEBHOOK_URL, event);

    const webhooks = await webflow.Webhooks.list({ forceAll: true });
    console.log("Finished: ");
    console.log(webhooks);
} catch (err) {
    printError(err);
}
