import {
  BRIDGED_STATUSES,
  CONTROL_EVENT_BUS_NAME_ENV_VAR,
  OPENHI_REPO_TAG_KEY_ENV_VAR,
  OPENHI_TAG_KEY_PREFIX_ENV_VAR,
  PLATFORM_DEPLOY_BRIDGE_ACTOR_SYSTEM
} from "./chunk-SVXLZCF7.mjs";
import {
  require_lib
} from "./chunk-KMEWULMX.mjs";
import {
  __toESM
} from "./chunk-LZOMFHX3.mjs";

// src/workflows/control-plane/platform-deploy-bridge/platform-deploy-bridge.handler.ts
var import_workflows = __toESM(require_lib());
import {
  CloudFormationClient,
  DescribeStacksCommand
} from "@aws-sdk/client-cloudformation";
import { EventBridgeClient } from "@aws-sdk/client-eventbridge";
var isBridgedStatus = (status) => BRIDGED_STATUSES.includes(status);
var cfnClient;
var ebClient;
var getCfnClient = () => {
  if (!cfnClient) {
    cfnClient = new CloudFormationClient({});
  }
  return cfnClient;
};
var getEbClient = () => {
  if (!ebClient) {
    ebClient = new EventBridgeClient({});
  }
  return ebClient;
};
var parseStackArn = (stackArn) => {
  const parts = stackArn.split(":");
  if (parts.length < 6 || parts[0] !== "arn" || parts[2] !== "cloudformation") {
    return void 0;
  }
  return { region: parts[3], accountId: parts[4] };
};
var parseStackName = (stackArn) => {
  const tail = stackArn.split(":").slice(5).join(":");
  const segments = tail.split("/");
  return segments.length >= 2 ? segments[1] : void 0;
};
var handler = async (event) => {
  const detail = event.detail;
  const status = detail?.["status-details"]?.status;
  if (!status || !isBridgedStatus(status)) {
    return;
  }
  const stackId = detail["stack-id"];
  if (!stackId) {
    console.warn("platform-deploy-bridge: event missing stack-id; dropping");
    return;
  }
  const arnParts = parseStackArn(stackId);
  if (!arnParts) {
    console.warn(
      `platform-deploy-bridge: unparseable stack ARN ${stackId}; dropping`
    );
    return;
  }
  const cfn = getCfnClient();
  const described = await cfn.send(
    new DescribeStacksCommand({ StackName: stackId })
  );
  const stack = described.Stacks?.[0];
  if (!stack) {
    console.warn(
      `platform-deploy-bridge: DescribeStacks returned no stack for ${stackId}; dropping`
    );
    return;
  }
  const allTags = (stack.Tags ?? []).filter(
    (t) => Boolean(t.Key && t.Value !== void 0)
  ).map((t) => ({ key: t.Key, value: t.Value }));
  const repoTagKey = process.env[OPENHI_REPO_TAG_KEY_ENV_VAR];
  if (!repoTagKey) {
    throw new Error(
      `platform-deploy-bridge: ${OPENHI_REPO_TAG_KEY_ENV_VAR} env var is required`
    );
  }
  const tagKeyPrefix = process.env[OPENHI_TAG_KEY_PREFIX_ENV_VAR];
  if (!tagKeyPrefix) {
    throw new Error(
      `platform-deploy-bridge: ${OPENHI_TAG_KEY_PREFIX_ENV_VAR} env var is required`
    );
  }
  const isOpenHiStack = allTags.some((t) => t.key === repoTagKey);
  if (!isOpenHiStack) {
    return;
  }
  const stackTags = allTags.filter((t) => t.key.startsWith(tagKeyPrefix));
  const stackName = stack.StackName ?? parseStackName(stackId);
  if (!stackName) {
    console.warn(
      `platform-deploy-bridge: could not resolve stack name for ${stackId}; dropping`
    );
    return;
  }
  const detailPayload = {
    stackName,
    stackId,
    region: arnParts.region,
    accountId: arnParts.accountId,
    status,
    ...detail["status-details"]["status-reason"] !== void 0 ? { statusReason: detail["status-details"]["status-reason"] } : {},
    stackTags,
    cloudformationEventTime: event.time
  };
  const controlBusName = process.env[CONTROL_EVENT_BUS_NAME_ENV_VAR];
  if (!controlBusName) {
    throw new Error(
      `platform-deploy-bridge: ${CONTROL_EVENT_BUS_NAME_ENV_VAR} env var is required`
    );
  }
  await (0, import_workflows.publishWorkflowEvent)(
    getEbClient(),
    import_workflows.PlatformDeploymentCompletedV1,
    detailPayload,
    { actor: { system: PLATFORM_DEPLOY_BRIDGE_ACTOR_SYSTEM } },
    {
      busNameByPlane: { [import_workflows.OPENHI_CONTROL_SOURCE]: controlBusName }
    }
  );
};
export {
  handler
};
//# sourceMappingURL=platform-deploy-bridge.handler.mjs.map