import { createManifestHandler } from "@saleor/app-sdk/handlers/next";
import { AppExtension, AppManifest } from "@saleor/app-sdk/types";

import packageJson from "@/package.json";

import { orderCreatedWebhook } from "./webhooks/order-created";
import { orderFulfilledWebhook } from "./webhooks/order-fulfilled";
import { orderCancelledWebhook } from "./webhooks/order-cancelled";
import { orderFilterShippingMethodsWebhook } from "./webhooks/order-filter-shipping-methods";

/**
 * App SDK helps with the valid Saleor App Manifest creation. Read more:
 * https://github.com/saleor/saleor-app-sdk/blob/main/docs/api-handlers.md#manifest-handler-factory
 */
export default createManifestHandler({
  async manifestFactory({ appBaseUrl, request, schemaVersion }) {
    /**
     * Allow to overwrite default app base url, to enable Docker support.
     *
     * See docs: https://docs.saleor.io/docs/3.x/developer/extending/apps/local-app-development
     */
    const iframeBaseUrl = process.env.APP_IFRAME_BASE_URL ?? appBaseUrl;
    const apiBaseURL = process.env.APP_API_BASE_URL ?? appBaseUrl;

    const extensionsForSaleor3_22: AppExtension[] = [
        {
          url: apiBaseURL + "/api/server-widget",
          permissions: [],
          mount: "PRODUCT_DETAILS_WIDGETS",
          label: "Product Timestamps",
          target: "WIDGET",
          options: {
            widgetTarget: {
              method: "POST",
            },
          },
        },
        {
          url: iframeBaseUrl+"/client-widget",
          permissions: [],
          mount: "ORDER_DETAILS_WIDGETS",
          label: "Order widget example",
          target: "WIDGET",
          options: {
            widgetTarget: {
              method: "GET",
            },
          },
        },
      ]

    const saleorMajor = schemaVersion && schemaVersion[0];
    const saleorMinor = schemaVersion && schemaVersion[1]

    const is3_22 = saleorMajor === 3 && saleorMinor === 22;

    const extensions = is3_22 ? extensionsForSaleor3_22 : [];

    const manifest: AppManifest = {
      name: "Core Extensions",
      tokenTargetUrl: `${apiBaseURL}/api/register`,
      appUrl: iframeBaseUrl,
      permissions: [
        "MANAGE_ORDERS",
      ],
      id: "saleor.core-extensions",
      version: packageJson.version,
      webhooks: [
        orderCreatedWebhook.getWebhookManifest(apiBaseURL),
        orderFulfilledWebhook.getWebhookManifest(apiBaseURL),
        orderCancelledWebhook.getWebhookManifest(apiBaseURL),
        orderFilterShippingMethodsWebhook.getWebhookManifest(apiBaseURL),
      ],
      /**
       * Optionally, extend Dashboard with custom UIs
       * https://docs.saleor.io/docs/3.x/developer/extending/apps/extending-dashboard-with-apps
       */
      extensions: extensions,
      author: "Saleor Commerce",
      brand: {
        logo: {
          default: `${apiBaseURL}/logo.png`,
        },
      },
    };

    return manifest;
  },
});
