import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("workflows");
function convertJsonSchemaToFields(schema) {
  if (!schema || !schema.properties) return [];
  const fields = [];
  const properties = schema.properties;
  const required = schema.required || [];
  for (const [name, prop] of Object.entries(properties)) {
    const propDef = prop;
    const field = {
      name,
      type: mapJsonSchemaTypeToFieldType(propDef),
      label: propDef.title || name,
      required: required.includes(name),
      placeholder: propDef.description || void 0
    };
    if (propDef.enum) {
      field.options = propDef.enum;
    }
    if (propDef.default !== void 0) {
      field.defaultValue = String(propDef.default);
    }
    fields.push(field);
  }
  return fields;
}
function mapJsonSchemaTypeToFieldType(propDef) {
  if (propDef.enum) return "select";
  switch (propDef.type) {
    case "string":
      if (propDef.format === "email") return "email";
      if (propDef.format === "uri") return "url";
      if (propDef.format === "date") return "date";
      if (propDef.format === "time") return "time";
      if (propDef.format === "date-time") return "datetime-local";
      if (propDef.maxLength && propDef.maxLength > 200) return "textarea";
      return "text";
    case "number":
    case "integer":
      return "number";
    case "boolean":
      return "checkbox";
    default:
      return "text";
  }
}
function nodeToFormValues(node) {
  const nodeData = node.data;
  const values = {
    stepName: nodeData?.stepName || nodeData?.label || "",
    description: nodeData?.description || "",
    timeout: nodeData?.timeout || ""
  };
  if (node.type === "userTask") {
    values.assignedTo = nodeData?.assignedTo || "";
    values.assignedToRoles = nodeData?.assignedToRoles?.join(", ") || "";
    values.formKey = nodeData?.formKey || "";
    if (nodeData?.userTaskConfig) {
      values.assignmentRule = nodeData.userTaskConfig.assignmentRule || nodeData.assignmentRule || "";
      values.slaDuration = nodeData.userTaskConfig.slaDuration || nodeData.slaDuration || "";
      values.escalationRules = nodeData.userTaskConfig.escalationRules || nodeData.escalationRules || [];
    }
    if (nodeData?.userTaskConfig?.formSchema) {
      const schema = nodeData.userTaskConfig.formSchema;
      if (schema.fields && Array.isArray(schema.fields)) {
        values.formFields = schema.fields;
      } else if (schema.properties) {
        values.formFields = convertJsonSchemaToFields(schema);
      } else {
        values.formFields = [];
      }
    } else {
      values.formFields = [];
    }
  }
  if (node.type === "automated") {
    values.activityType = nodeData?.activityType || "";
    values.activityId = nodeData?.activityId || "";
    values.stepActivities = nodeData?.activities || [];
  }
  if (node.type === "subWorkflow" && nodeData?.config) {
    values.subWorkflowId = nodeData.config.subWorkflowId || "";
    values.subWorkflowVersion = nodeData.config.version?.toString() || "";
    if (nodeData.config.inputMapping) {
      values.inputMappings = Object.entries(nodeData.config.inputMapping).map(([key, value]) => ({
        key,
        value
      }));
    } else {
      values.inputMappings = [];
    }
    if (nodeData.config.outputMapping) {
      values.outputMappings = Object.entries(nodeData.config.outputMapping).map(([key, value]) => ({
        key,
        value
      }));
    } else {
      values.outputMappings = [];
    }
  }
  if (node.type === "waitForSignal" && nodeData?.signalConfig) {
    values.signalName = nodeData.signalConfig.signalName || "";
    values.signalTimeout = nodeData.signalConfig.timeout || "PT5M";
  }
  if (node.type === "start" && nodeData?.preConditions) {
    values.preConditions = nodeData.preConditions;
  } else if (node.type === "start") {
    values.preConditions = [];
  }
  const advancedFields = {};
  if (nodeData?.userTaskConfig) {
    advancedFields.userTaskConfig = nodeData.userTaskConfig;
  }
  if (nodeData?.retryPolicy) {
    advancedFields.retryPolicy = nodeData.retryPolicy;
  }
  values.advancedConfig = Object.keys(advancedFields).length > 0 ? JSON.stringify(advancedFields, null, 2) : "";
  return values;
}
function formValuesToNodeUpdates(values, node) {
  const updates = {
    stepName: values.stepName,
    label: values.stepName,
    // Keep label for backward compatibility
    description: values.description || void 0,
    timeout: values.timeout || void 0
  };
  if (node.type === "userTask") {
    updates.assignedTo = values.assignedTo || void 0;
    updates.assignedToRoles = values.assignedToRoles ? values.assignedToRoles.split(",").map((r) => r.trim()).filter(Boolean) : [];
    updates.formKey = values.formKey || void 0;
    updates.userTaskConfig = {
      ...values.formFields && values.formFields.length > 0 && {
        formSchema: {
          fields: values.formFields
        }
      },
      ...values.assignedTo && { assignedTo: values.assignedTo },
      ...values.assignedToRoles && {
        assignedToRoles: values.assignedToRoles.split(",").map((r) => r.trim()).filter(Boolean)
      },
      // Preserve advanced fields
      ...values.assignmentRule && { assignmentRule: values.assignmentRule },
      ...values.slaDuration && { slaDuration: values.slaDuration },
      ...values.escalationRules && values.escalationRules.length > 0 && {
        escalationRules: values.escalationRules
      }
    };
  }
  if (node.type === "automated") {
    updates.activityType = values.activityType || void 0;
    updates.activityId = values.activityId || void 0;
    if (values.stepActivities && values.stepActivities.length > 0) {
      updates.activities = values.stepActivities;
    }
  }
  if (node.type === "subWorkflow") {
    const config = {};
    if (values.subWorkflowId) {
      config.subWorkflowId = values.subWorkflowId;
    }
    if (values.subWorkflowVersion) {
      const versionNum = parseInt(values.subWorkflowVersion, 10);
      if (!isNaN(versionNum)) {
        config.version = versionNum;
      }
    }
    if (values.inputMappings && values.inputMappings.length > 0) {
      config.inputMapping = values.inputMappings.filter((m) => m.key && m.value).reduce((acc, m) => ({ ...acc, [m.key]: m.value }), {});
    }
    if (values.outputMappings && values.outputMappings.length > 0) {
      config.outputMapping = values.outputMappings.filter((m) => m.key && m.value).reduce((acc, m) => ({ ...acc, [m.key]: m.value }), {});
    }
    if (Object.keys(config).length > 0) {
      updates.config = config;
    }
  }
  if (node.type === "waitForSignal") {
    const config = {};
    if (values.signalName) {
      config.signalName = values.signalName;
    }
    if (values.signalTimeout) {
      config.timeout = values.signalTimeout;
    }
    if (Object.keys(config).length > 0) {
      updates.signalConfig = config;
    }
  }
  if (node.type === "start") {
    if (values.preConditions && values.preConditions.length > 0) {
      updates.preConditions = values.preConditions.filter((pc) => pc.ruleId && pc.ruleId.trim());
    } else {
      updates.preConditions = [];
    }
  }
  if (values.advancedConfig && values.advancedConfig.trim()) {
    try {
      const parsed = JSON.parse(values.advancedConfig);
      Object.assign(updates, parsed);
    } catch (error) {
      logger.error("Invalid JSON in Advanced Configuration", { err: error });
      throw new Error("Invalid JSON in Advanced Configuration. Please check your syntax.");
    }
  }
  return updates;
}
function isJsonSchemaFormat(node) {
  const nodeData = node.data;
  if (node.type !== "userTask") return false;
  const schema = nodeData?.userTaskConfig?.formSchema;
  if (!schema) return false;
  return Boolean(schema.properties && !schema.fields);
}
export {
  formValuesToNodeUpdates,
  isJsonSchemaFormat,
  nodeToFormValues
};
//# sourceMappingURL=nodeFormTransforms.js.map
