"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/overview-dashboard/sqs-dlq-stats-widget-function.lambda.ts
var sqs_dlq_stats_widget_function_lambda_exports = {};
__export(sqs_dlq_stats_widget_function_lambda_exports, {
  handler: () => handler
});
module.exports = __toCommonJS(sqs_dlq_stats_widget_function_lambda_exports);
var import_aws_sdk = require("aws-sdk");
var DOCS = `

### Widget parameters
Param | Description
---|---
**title** | Title of the widget
**emptyQueueMessage** | Message to display when there are no visible messages in any of the queues
**nonEmptyQueueMessage** | Message to display when any of the queue contains a message
**queues** | Object containing information about the queues to display

### Example parameters
\`\`\` yaml
{
    "description": "",
    "title": "SQS DLQ",
    "emptyQueueMessage": "There are no messages in the DLQs. This is normal and no action is required.",
    "nonEmptyQueueMessage": "There are some message in the DLQ. The table below lists the queues with non-empty DLQs. Please check the DLQs and re-drive the messages.",
    "queues": {
        "construct-hub-dev-ConstructHubOrchestrationDLQ9C6D9BD4-rlooG5g8o3YA": {
            "name": "Orchestration DLQ",
            "queueName": "construct-hub-dev-ConstructHubOrchestrationDLQ9C6D9BD4-rlooG5g8o3YA",
            "reDriveFunctionArn": "arn:aws:lambda:us-east-2:123457424:function:construct-hub-dev-ConstructHubOrchestrationRedrive-bWYSY5KWfUUU"
        },
        "construct-hub-dev-ConstructHubIngestionDLQ3E96A5F2-6niMeQlEH0X0": {
            "name": "Ingestion DLQ",
            "queueName": "construct-hub-dev-ConstructHubIngestionDLQ3E96A5F2-6niMeQlEH0X0"
        },
        "construct-hub-dev-ConstructHubSourcesStagerDLQ80BD2600-AlCVN3KCXFPo": {
            "name": "NPM JS Stager DLQ",
            "queueName": "construct-hub-dev-ConstructHubSourcesStagerDLQ80BD2600-AlCVN3KCXFPo"
        }
    }
}
\`\`\`
`;
var DURATION = 5;
async function handler(event) {
  var _a, _b;
  console.log(JSON.stringify(event));
  try {
    if (event.describe) {
      return DOCS;
    }
    const queues = (_a = event.widgetContext.params) == null ? void 0 : _a.queues;
    if (Object.keys(queues).length === 0) {
      return "No queue names specified";
    }
    const data = await getVisibleMessageCount(queues);
    const heading = `<h4>${event.widgetContext.title}</h4>`;
    const description = event.widgetContext.params.description ? `<p>${event.widgetContext.params.description}</p>` : "";
    let rest = "";
    if (Object.keys(data).length > 0 && Object.values(data).some((d) => d > 0)) {
      const filteredData = Object.entries(data).filter(([_, count]) => count > 0).reduce(
        (acc, [queueName, count]) => ({ ...acc, [queueName]: count }),
        {}
      );
      const table = generateTable(filteredData, queues, event.widgetContext);
      console.log(table);
      rest = `<p>${event.widgetContext.params.nonEmptyQueueMessage}</p>${table}`;
    } else {
      rest = `<p>${event.widgetContext.params.emptyQueueMessage}</p>`;
    }
    return [heading, description, rest].join("\n");
  } catch (error) {
    if (error instanceof Error) {
      return {
        markdown: [
          "**\u26A0\uFE0F An error occurred**",
          `- **name:** \`${error.name}\``,
          `- **message:** ${error.message}`,
          "- **stack:**",
          "  ```",
          (_b = error.stack) == null ? void 0 : _b.replace(/^/g, "  "),
          "  ```"
        ].join("\n")
      };
    }
    throw error;
  }
}
var getVisibleMessageCount = async (queueConfigs) => {
  const queues = Object.values(queueConfigs);
  const params = {
    StartTime: new Date((/* @__PURE__ */ new Date()).getTime() - DURATION * 60 * 1e3),
    // 5 minutes ago
    EndTime: /* @__PURE__ */ new Date(),
    // now
    ScanBy: "TimestampDescending",
    MetricDataQueries: queues.map((queue, index) => ({
      Id: `m${index}`,
      MetricStat: {
        Period: 60,
        Stat: "Maximum",
        Metric: {
          Namespace: "AWS/SQS",
          MetricName: "ApproximateNumberOfMessagesVisible",
          Dimensions: [
            {
              Name: "QueueName",
              Value: queue.queueName
            }
          ]
        }
      }
    }))
  };
  const cloudwatch = new import_aws_sdk.CloudWatch();
  const response = await cloudwatch.getMetricData(params).promise();
  const data = (response.MetricDataResults ?? []).reduce((acc, result) => {
    var _a;
    if (result.Id) {
      const id = Number.parseInt(result.Id.replace("m", ""), 10);
      return { ...acc, [queues[id].queueName]: ((_a = result.Values) == null ? void 0 : _a[0]) ?? 0 };
    }
    return acc;
  }, {});
  return data;
};
function generateTable(data, queueConfigs, widgetContext) {
  const rows = Object.entries(data).map(([queueName, count]) => {
    const queueConfig = queueConfigs[queueName];
    if (queueConfig) {
      const url = sqsQueueUrl(queueName, widgetContext);
      const reDriveButton = (queueConfig == null ? void 0 : queueConfig.reDriveFunctionArn) ? `<a class="btn btn-primary">ReDrive</a><cwdb-action action="call" display="widget" endpoint="${queueConfig.reDriveFunctionArn}" event="click"></<cwdb-action>` : "";
      const queueLink = `<a class="btn ${!reDriveButton ? "btn-primary" : ""}" href="${url}">Goto Queue</a>`;
      const row = [queueConfig.name, count, `${queueLink} ${reDriveButton}`].map((d) => `<td>${d}</td>`).join("");
      return `<tr>${row}</tr>`;
    }
    return false;
  }).filter(Boolean);
  const tableHeader = ["Queue Name", "Visible Messages", "Action"].map(
    (h) => `<th>${h}</th>`
  );
  const tableHeaderRow = `<tr>${tableHeader.join("")}</tr>`;
  const table = ["<table>", tableHeaderRow, ...rows, "</table>"].join("\n");
  return table;
}
function sqsQueueUrl(queueName, widgetContext) {
  return `/sqs/v2/home#/queues/https%3A%2F%2Fsqs.${process.env.AWS_REGION}.amazonaws.com%2F${widgetContext.accountId}%2F${queueName}`;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  handler
});
//# sourceMappingURL=index.js.map
