import { DefineFunction, Schema, SlackFunction } from "deno-slack-sdk/mod.ts";
export const CreateContentFunctionDefinition = DefineFunction({
  callback_id: "create_content_function",
  title: "Create content function",
  description: "A crete content function",
  source_file: "functions/create_content_function.ts",
  input_parameters: {
    properties: {
      token: {
        type: Schema.slack.types.oauth2,
        oauth2_provider_key: "hygraph",
      },
      project_id: {
        type: Schema.slack.types.string,
        description: "The project to create content for",
      },
      model_id: {
        type: Schema.slack.types.string,
        description: "The model to create content for",
      },
      channel_id: {
        type: Schema.slack.types.channel_id,
        description: "The channel to post the message in",
      }
    },
    required: ["token", "project_id", "model_id", "channel_id"],
  },
  output_parameters: {
      properties: {
        contentId: {
          type: Schema.types.string,
          description: "ID of the created content",
        },
      },
      required: ["contentId"],
    },
});
export default SlackFunction(
  CreateContentFunctionDefinition,
  async ({ inputs, client }) => {
    
    const tokenResponse = await client.apps.auth.external.get({
      external_token_id: inputs.token,
    });
    if (tokenResponse.error) {
      const error = `Failed to retrieve the external auth token due to ${tokenResponse.error}`;
      return { error };
    }
    
    const externalToken = tokenResponse.external_token;
    
    const response = await fetch(
      "https://eu-central-1.api.hygraph.com/graphql",
      {
        method: "POST",
        body: JSON.stringify({
          query: `query Viewer {
            _viewer {
                ... on UserViewer {
                    id
                    user {
                        id
                        profile {
                            email
                            name
                        }
                    }
                    project(id: "${inputs.project_id}") {
                      environment(id: "master"){
                          authToken
                      }
                    }
                }
            }
        }
        `,
        }),
        headers: new Headers({
          Authorization: `Bearer ${externalToken}`,
          "Content-Type": "application/json",
        }),
      }
    );
    if (response.status != 200) {
      const body = await response.text();
      const error = `Failed to call my endpoint! (status: ${response.status}, body: ${body})`;
      return { error };
    }
    const responseBody = await response.json();
    const uuid = crypto.randomUUID();
    const contentApiToken = responseBody.data._viewer.project.environment.authToken;
    const createContentResponse = await fetch(
      "https://api-eu-central-1.hygraph.com/v2/cmaz8u024000b07w2o46szn1y/master",
      {
        method: "POST",
        body: JSON.stringify({
          query: `mutation createContent($data: DemoModel23May20250843CreateInput!) {
            createDemoModel23May20250843(data: $data) {
              id
            }
          }`,
          variables: {
            data: {
              title: `Sample Content ${uuid}`,
              slug: `sampleContent${uuid}s`,
              
            },
          },
        }),
        headers: new Headers({
          Authorization: `Bearer ${contentApiToken}`,
          "Content-Type": "application/json",
        }),
      }
    );
    if (createContentResponse.status != 200) {
      const body = await createContentResponse.text();
      const error = `Failed to create content! (status: ${createContentResponse.status}, body: ${body})`;
      return { error };
    }
    client.chat.postMessage({
      channel: inputs.channel_id,
      text: `Content created successfully with ID: ${uuid}`,
    });
    return { outputs: { contentId: uuid } };
  }
);