import { resolveSpecialValue } from "./value-resolver.js";
async function executeActions(actions, context) {
  const startTime = Date.now();
  const results = [];
  const errors = [];
  for (const action of actions) {
    try {
      const result = await executeAction(action, context);
      results.push(result);
      if (result.error) {
        errors.push(`Action ${action.type}: ${result.error}`);
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      errors.push(`Action ${action.type}: ${errorMessage}`);
      results.push({
        action,
        success: false,
        error: errorMessage,
        executionTime: 0
      });
    }
  }
  const totalTime = Date.now() - startTime;
  return {
    success: results.every((r) => r.success),
    results,
    totalTime,
    errors: errors.length > 0 ? errors : void 0
  };
}
async function executeAction(action, context) {
  const startTime = Date.now();
  try {
    const handler = getActionHandler(action.type);
    const result = await handler(action, context);
    const executionTime = Date.now() - startTime;
    return {
      action,
      success: true,
      result,
      executionTime
    };
  } catch (error) {
    const executionTime = Date.now() - startTime;
    const errorMessage = error instanceof Error ? error.message : String(error);
    return {
      action,
      success: false,
      error: errorMessage,
      executionTime
    };
  }
}
function getActionHandler(actionType) {
  const handlers = {
    ALLOW_TRANSITION: handleAllowTransition,
    BLOCK_TRANSITION: handleBlockTransition,
    LOG: handleLog,
    SHOW_ERROR: handleShowError,
    SHOW_WARNING: handleShowWarning,
    SHOW_INFO: handleShowInfo,
    NOTIFY: handleNotify,
    SET_FIELD: handleSetField,
    CALL_WEBHOOK: handleCallWebhook,
    EMIT_EVENT: handleEmitEvent
  };
  const handler = handlers[actionType];
  if (!handler) {
    throw new Error(`Unknown action type: ${actionType}`);
  }
  return handler;
}
async function handleAllowTransition(action, context) {
  return {
    type: "ALLOW_TRANSITION",
    allowed: true,
    message: interpolateMessage(action.config?.message || "Transition allowed", context)
  };
}
async function handleBlockTransition(action, context) {
  return {
    type: "BLOCK_TRANSITION",
    allowed: false,
    message: interpolateMessage(action.config?.message || "Transition blocked", context)
  };
}
async function handleLog(action, context) {
  const level = action.config?.level || "info";
  const message = interpolateMessage(action.config?.message || "", context);
  return {
    type: "LOG",
    level,
    message,
    timestamp: (/* @__PURE__ */ new Date()).toISOString()
  };
}
async function handleShowError(action, context) {
  const message = interpolateMessage(action.config?.message || "", context);
  return {
    type: "SHOW_ERROR",
    severity: "error",
    message
  };
}
async function handleShowWarning(action, context) {
  const message = interpolateMessage(action.config?.message || "", context);
  return {
    type: "SHOW_WARNING",
    severity: "warning",
    message
  };
}
async function handleShowInfo(action, context) {
  const message = interpolateMessage(action.config?.message || "", context);
  return {
    type: "SHOW_INFO",
    severity: "info",
    message
  };
}
async function handleNotify(action, context) {
  const recipients = action.config?.recipients || [];
  const message = interpolateMessage(action.config?.message || "", context);
  const subject = interpolateMessage(action.config?.subject || "", context);
  const template = action.config?.template;
  if (!Array.isArray(recipients)) {
    throw new Error("NOTIFY action requires recipients to be an array");
  }
  if (recipients.length === 0) {
    throw new Error("NOTIFY action requires at least one recipient");
  }
  return {
    type: "NOTIFY",
    recipients,
    subject,
    message,
    template
  };
}
async function handleSetField(action, context) {
  const field = action.config?.field;
  const value = resolveValue(action.config?.value, context);
  if (!field) {
    throw new Error("SET_FIELD action requires a field name");
  }
  if (typeof field !== "string" || field.trim() === "") {
    throw new Error("SET_FIELD action requires a non-empty field name");
  }
  return {
    type: "SET_FIELD",
    field,
    value
  };
}
async function handleCallWebhook(action, context) {
  const url = interpolateMessage(action.config?.url || "", context);
  const method = action.config?.method || "POST";
  const headers = action.config?.headers || {};
  const body = action.config?.body;
  if (!url || url.trim() === "") {
    throw new Error("CALL_WEBHOOK action requires a non-empty URL");
  }
  const validMethods = ["GET", "POST", "PUT", "PATCH", "DELETE"];
  if (!validMethods.includes(method.toUpperCase())) {
    throw new Error(
      `CALL_WEBHOOK action requires a valid HTTP method (${validMethods.join(", ")})`
    );
  }
  return {
    type: "CALL_WEBHOOK",
    url,
    method: method.toUpperCase(),
    headers,
    body,
    status: "pending"
  };
}
async function handleEmitEvent(action, context) {
  const eventName = action.config?.event;
  const payload = action.config?.payload || {};
  if (!eventName) {
    throw new Error("EMIT_EVENT action requires an event name");
  }
  if (typeof eventName !== "string" || eventName.trim() === "") {
    throw new Error("EMIT_EVENT action requires a non-empty event name");
  }
  return {
    type: "EMIT_EVENT",
    event: eventName,
    payload
  };
}
function interpolateMessage(template, context) {
  if (!template) {
    return "";
  }
  return template.replace(/\{\{([^}]+)\}\}/g, (match, path) => {
    const trimmedPath = path.trim();
    const value = resolveValue(`{{${trimmedPath}}}`, context);
    if (value === void 0 || value === null) {
      return match;
    }
    return String(value);
  });
}
function resolveValue(value, context) {
  if (typeof value !== "string") {
    return value;
  }
  if (value.startsWith("{{") && value.endsWith("}}")) {
    return resolveSpecialValue(value, context);
  }
  return value;
}
export {
  executeAction,
  executeActions,
  interpolateMessage
};
//# sourceMappingURL=action-executor.js.map
