/**
 * Actions are individual steps that you add to an integration
 * built with the low-code designer. Each step receives a set
 * of inputs and connection information for a third-party API,
 * does work, and returns a result.
 *
 * For information on actions, see
 * https://prismatic.io/docs/custom-connectors/actions/
 */

import { action, input, util } from "@prismatic-io/spectral";
import {
  inputs as httpClientInputs,
  sendRawRequest,
} from "@prismatic-io/spectral/http";
import { createAcmeClient } from "./client";

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

export const connectionInput = input({
  label: "Acme Connection",
  required: true,
  type: "connection",
});

export const postIdInput = input({
  label: "Post ID",
  required: true,
  type: "string",
  clean: util.types.toNumber,
});

/* List all posts in JSONPlaceholder */
const listPosts = action({
  display: {
    label: "List All Posts",
    description: "List all posts from JSONPlaceholder",
  },
  inputs: {
    // Declare an input for this action
    acmeConnection: connectionInput,
  },
  perform: async (context, { acmeConnection }) => {
    // Initialize our reusable HTTP client
    const acmeClient = createAcmeClient(acmeConnection);

    // Make a synchronous GET call to "{ baseUrl }/posts":
    const response = await acmeClient.get<Post[]>("/posts");

    // Return the data that we got back
    return { data: response.data };
  },
  // Show an example payload in the Prismatic UI:
  examplePayload: {
    data: [
      {
        id: 1,
        userId: 1,
        title: "Example post",
        body: "Example body",
      },
      {
        id: 2,
        userId: 1,
        title: "Another post",
        body: "Another body",
      },
    ],
  },
});

/* Get a specific post from JSONPlaceholder by ID */
const getPost = action({
  display: {
    label: "Get Post",
    description: "Get a post by ID",
  },
  inputs: {
    acmeConnection: connectionInput,
    postId: postIdInput,
  },
  perform: async (context, { acmeConnection, postId }) => {
    const acmeClient = createAcmeClient(acmeConnection);
    const response = await acmeClient.get<Post>(`/posts/${postId}`);
    return { data: response.data };
  },
  examplePayload: {
    data: {
      id: 1,
      userId: 1,
      title: "Example post",
      body: "Example body",
    },
  },
});

/* Add a new post to JSONPlaceholder */
const addPost = action({
  display: {
    label: "Add Post",
    description: "Create a sample post (JSONPlaceholder simulates writes without saving them)",
  },
  // We can define some inputs inline if they're not reused:
  inputs: {
    acmeConnection: connectionInput,
    title: input({ label: "Post Title", type: "string" }),
    body: input({ label: "Post Body", type: "string" }),
    userId: input({
      label: "User ID",
      type: "string",
      clean: util.types.toNumber,
    }),
  },
  perform: async (context, { acmeConnection, title, body, userId }) => {
    const acmeClient = createAcmeClient(acmeConnection);
    const response = await acmeClient.post<Post>("/posts", {
      title,
      body,
      userId,
    });
    return { data: response.data };
  },
  examplePayload: {
    data: {
      id: 1,
      userId: 1,
      title: "Example post",
      body: "Example body",
    },
  },
});

const rawRequest = action({
  display: {
    label: "Raw Request",
    description: "Send an HTTP request to any Acme endpoint",
  },
  inputs: {
    acmeConnection: connectionInput,
    ...httpClientInputs,
    url: {
      // Optional; this adds component-specific instructions to the URL input
      ...httpClientInputs.url,
      comments:
        "The base URL from your connection is already included (https://jsonplaceholder.typicode.com). For example, to connect to https://jsonplaceholder.typicode.com/posts, only /posts is entered in this field.",
      example: "/posts",
    },
  },
  perform: async (context, { acmeConnection, ...httpClientInputs }) => {
    const { data } = await sendRawRequest(
      util.types.toString(acmeConnection.fields.baseUrl),
      httpClientInputs,
      acmeConnection.fields.apiKey
        ? { Authorization: `Bearer ${acmeConnection.fields.apiKey}` }
        : {}, // JSONPlaceholder does not require authentication
    );
    return { data };
  },
});

export default { addPost, getPost, listPosts, rawRequest };
