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

import packageJson from "@/package.json";

import {
  orderConfirmedWebhook,
  orderFulfilledWebhook,
  orderCancelledWebhook,
} from "./webhooks/order-notifications";

/**
 * 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 manifest: AppManifest = {
      name: "Core Extensions",
      tokenTargetUrl: `${apiBaseURL}/api/register`,
      appUrl: iframeBaseUrl,
      permissions: [
        "MANAGE_ORDERS",
      ],
      id: "saleor-core-extensions",
      version: packageJson.version,
      webhooks: [
        orderConfirmedWebhook.getWebhookManifest(apiBaseURL),
        orderFulfilledWebhook.getWebhookManifest(apiBaseURL),
        orderCancelledWebhook.getWebhookManifest(apiBaseURL),
      ],
      extensions: [],
      author: "ManoonOils",
      brand: {
        logo: {
          default: `${apiBaseURL}/logo.png`,
        },
      },
    };

    return manifest;
  },
});
