"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/handler/github-resource/github-resource-handler.lambda.ts
var github_resource_handler_lambda_exports = {};
__export(github_resource_handler_lambda_exports, {
  handler: () => handler
});
module.exports = __toCommonJS(github_resource_handler_lambda_exports);
var import_client_secrets_manager = require("@aws-sdk/client-secrets-manager");
var import_client_ssm = require("@aws-sdk/client-ssm");
var import_core = require("@octokit/core");
var onEvent = async (event) => {
  console.log(`Event: ${JSON.stringify(event)}`);
  const clientConfig = { region: event.ResourceProperties.awsRegion };
  const ssmClient = new import_client_ssm.SSM(clientConfig);
  const smClient = new import_client_secrets_manager.SecretsManager(clientConfig);
  const githubTokenSecret = await smClient.getSecretValue({ SecretId: event.ResourceProperties.githubTokenSecret });
  const octokit = new import_core.Octokit({ auth: githubTokenSecret.SecretString });
  const requestType = event.RequestType;
  switch (requestType) {
    case "Create":
      return onCreate(event, octokit, ssmClient);
    case "Update":
      return onUpdate(event, octokit, ssmClient);
    case "Delete":
      return onDelete(event, octokit, ssmClient);
    default:
      throw new Error(`Unexpected request type: '${requestType}'`);
  }
};
var onCreate = async (event, octokit, ssmClient) => {
  const {
    createRequestEndpoint,
    createRequestPayload,
    responseBodySSMParameterName
  } = event.ResourceProperties;
  const requestResult = await executeRequest(octokit, createRequestEndpoint, createRequestPayload);
  console.log("Created GitHub Resource");
  const PhysicalResourceId = await extractIdFromRequestResult(event, requestResult);
  await writeResponseBodyToSSMParameterIfNeeded(ssmClient, requestResult.data, responseBodySSMParameterName);
  return { PhysicalResourceId };
};
var onUpdate = async (event, octokit, ssmClient) => {
  const {
    updateRequestEndpoint,
    updateRequestPayload,
    createRequestResultParameter,
    responseBodySSMParameterName
  } = event.ResourceProperties;
  const PhysicalResourceId = event.PhysicalResourceId;
  if (!updateRequestEndpoint) {
    console.log("No update request endpoint specified, so we'll just ignore the update request.");
    return { PhysicalResourceId };
  }
  const updateEndpoint = replaceResultParamterInEndpoint(updateRequestEndpoint, createRequestResultParameter, PhysicalResourceId);
  const requestResult = await executeRequest(octokit, updateEndpoint, updateRequestPayload);
  console.log(`Updated GitHub Resource with id '${event.PhysicalResourceId}'`);
  await writeResponseBodyToSSMParameterIfNeeded(ssmClient, requestResult.data, responseBodySSMParameterName);
  return { PhysicalResourceId };
};
var onDelete = async (event, octokit, ssmClient) => {
  const {
    deleteRequestEndpoint,
    deleteRequestPayload,
    createRequestResultParameter,
    responseBodySSMParameterName
  } = event.ResourceProperties;
  const PhysicalResourceId = event.PhysicalResourceId;
  const deleteEndpoint = replaceResultParamterInEndpoint(deleteRequestEndpoint, createRequestResultParameter, PhysicalResourceId);
  const requestResult = await executeRequest(octokit, deleteEndpoint, deleteRequestPayload);
  const responseBody = requestResult.data;
  console.log(`Deleted GitHub Resource with id '${event.PhysicalResourceId}'`);
  await writeResponseBodyToSSMParameterIfNeeded(ssmClient, responseBody, responseBodySSMParameterName);
  return { PhysicalResourceId };
};
var executeRequest = async (octokit, endpoint, payload) => {
  const payloadToSend = payload ? JSON.parse(payload) : void 0;
  console.log(`Making a request to '${endpoint}'.`);
  const requestResult = await octokit.request(endpoint, payloadToSend);
  return requestResult;
};
var replaceResultParamterInEndpoint = (endpoint, createRequestResultParameter, createRequestResultValue) => createRequestResultParameter && createRequestResultValue ? endpoint.replace(":" + createRequestResultParameter, createRequestResultValue) : endpoint;
var toStringIfNotUndefined = (value) => value !== void 0 ? String(value) : void 0;
var writeResponseBodyToSSMParameterIfNeeded = async (ssmClient, responseBody, parameterName) => {
  if (parameterName) {
    console.log(`Write the response body to the ssm parameter '${parameterName}'`);
    await ssmClient.putParameter({ Name: parameterName, Value: JSON.stringify(responseBody), Overwrite: true });
  }
};
var extractIdFromRequestResult = async (event, requestResult) => {
  const { createRequestResultParameter } = event.ResourceProperties;
  console.log("Going to extract the parameter from the create result (if needed)");
  const createRequestResultOriginalValue = createRequestResultParameter ? requestResult.data[createRequestResultParameter] : void 0;
  const createRequestResultValue = toStringIfNotUndefined(createRequestResultOriginalValue);
  if (!createRequestResultValue && createRequestResultParameter) {
    throw new Error("Could not find '" + createRequestResultParameter + "' in request result: " + JSON.stringify(requestResult));
  }
  return createRequestResultValue;
};
var handler = onEvent;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  handler
});
