/**
 * When a customer deploys an instance of your integration,
 * they will walk through a configuration wizard. In this
 * example configuration wizard, we prompt the customer for
 * their authentication information, and then use that
 * information to fetch data for a dropdown menu.
 *
 * For more information on the code-native config wizards, see
 * https://prismatic.io/docs/integrations/code-native/config-wizard/
 */

import {
  type Connection,
  type Element,
  configPage,
  connectionConfigVar,
  dataSourceConfigVar,
} from "@prismatic-io/spectral";
import { createAcmeClient } from "./client";

export interface Post {
  id: number;
  userId: number;
  title: string;
  body: string;
}

export const configPages = {
  Connections: configPage({
    elements: {
      // Your end user will enter connection information on the first page
      "Acme Connection": connectionConfigVar({
        stableKey: "<%= configVars.connection.stableKey %>",
        dataType: "connection",
        inputs: {
          baseUrl: {
            label: "Acme Base URL",
            type: "string",
            required: true,
            default: "https://jsonplaceholder.typicode.com",
            example: "https://my-company.api.acme.com/",
          },
          apiKey: {
            label: "Acme API Key",
            placeholder: "Acme API Key",
            type: "password",
            required: false,
            comments: "JSONPlaceholder needs no API key.",
          },
        },
      }),
    },
  }),
  "Post Configuration": configPage({
    elements: {
      /**
       * Dynamically fetch data using the existing connection, and present the
       * data as a dropdown menu in the config wizard.
       */
      "Select Post": dataSourceConfigVar({
        stableKey: "<%= configVars.dataSource.stableKey %>",
        dataSourceType: "picklist",
        perform: async (context) => {
          // Create an authenticated reusable HTTP client from client.ts
          const client = createAcmeClient(context.configVars["Acme Connection"] as Connection);
          const { data: posts } = await client.get<Post[]>("/posts");
          const options: Element[] = posts.map((post) => ({
            key: `${post.id}`,
            label: post.title,
          }));
          return { result: options };
        },
      }),
    },
  }),
};
