/**
 * Datasources are used to dynamically fetch and display configuration
 * information within the configuration wizard. You can fetch data from
 * a third-party API, and present the data as input boxes, dropdown
 * menus, or JSON Forms.
 *
 * For information on data sources, see
 * https://prismatic.io/docs/custom-connectors/data-sources/
 */

import { type Element, dataSource, input } from "@prismatic-io/spectral";
import { createAcmeClient } from "./client";

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

/**
 * Create a dropdown menu, populated with posts
 * from an API, for use in the config wizard
 */
export const selectPost = dataSource({
  display: {
    label: "Select Post",
    description: "This data source fetches a list of posts, and presents them as a dropdown menu",
  },
  dataSourceType: "picklist",
  inputs: {
    acmeConnection: input({
      label: "Acme Connection",
      required: true,
      type: "connection",
    }),
  },
  perform: async (context, { acmeConnection }) => {
    const client = createAcmeClient(acmeConnection);
    const { data: posts } = await client.get<Post[]>("/posts");
    const options: Element[] = posts.map((post) => ({
      key: `${post.id}`,
      label: post.title,
    }));
    return { result: options };
  },
  examplePayload: {
    result: [
      { key: "1", label: "Example post" },
      { key: "2", label: "Another post" },
    ],
  },
});

export default { selectPost };
