import * as ruleEngine from "../../business_rules/lib/rule-engine.js";
import { findWorkflowDefinition } from "./find-definition.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("workflows");
async function validateWorkflowStart(em, options) {
  const { workflowId, version, context, locale = "en", tenantId, organizationId } = options;
  const definition = await findWorkflowDefinition(em, {
    workflowId,
    version,
    tenantId,
    organizationId
  });
  if (!definition) {
    return {
      canStart: false,
      errors: [{
        ruleId: "_DEFINITION_NOT_FOUND",
        message: `Workflow definition not found: ${workflowId}`,
        code: "DEFINITION_NOT_FOUND"
      }],
      validatedRules: []
    };
  }
  if (!definition.enabled) {
    return {
      canStart: false,
      errors: [{
        ruleId: "_DEFINITION_DISABLED",
        message: `Workflow is disabled: ${workflowId}`,
        code: "DEFINITION_DISABLED"
      }],
      validatedRules: []
    };
  }
  const startStep = definition.definition.steps.find(
    (s) => s.stepType === "START"
  );
  if (!startStep) {
    return {
      canStart: false,
      errors: [{
        ruleId: "_NO_START_STEP",
        message: "Workflow has no START step",
        code: "INVALID_DEFINITION"
      }],
      validatedRules: []
    };
  }
  const preConditions = startStep.preConditions || [];
  logger.debug("Evaluating START step pre-conditions", {
    component: "start-validator",
    startStep,
    preConditionCount: preConditions.length,
    preConditions
  });
  if (preConditions.length === 0) {
    logger.debug("No pre-conditions defined, allowing start", { component: "start-validator" });
    return {
      canStart: true,
      errors: [],
      validatedRules: []
    };
  }
  const errors = [];
  const validatedRules = [];
  for (const condition of preConditions) {
    const result = await ruleEngine.executeRuleByRuleId(em, {
      ruleId: condition.ruleId,
      // String identifier like "workflow_checkout_inventory_available"
      data: {
        workflowId,
        workflowContext: context
      },
      tenantId,
      organizationId,
      entityType: `workflow:${workflowId}:start`,
      entityId: "pre_start_validation",
      eventType: "validate_start",
      dryRun: true
      // Don't log execution during validation
    });
    validatedRules.push({
      ruleId: condition.ruleId,
      passed: result.conditionResult,
      executionTime: result.executionTime
    });
    if (result.error === "Rule not found") {
      if (condition.required) {
        errors.push({
          ruleId: condition.ruleId,
          message: getLocalizedMessage(condition, null, locale, `Business rule not found: ${condition.ruleId}`),
          code: "RULE_NOT_FOUND"
        });
      }
      continue;
    }
    if (result.error === "Rule is disabled") {
      if (condition.required) {
        errors.push({
          ruleId: condition.ruleId,
          message: getLocalizedMessage(condition, null, locale, `Business rule is disabled: ${result.ruleName}`),
          code: "RULE_DISABLED"
        });
      }
      continue;
    }
    if (result.error && condition.required) {
      errors.push({
        ruleId: condition.ruleId,
        message: getLocalizedMessage(condition, null, locale, `Rule error: ${result.error}`),
        code: "RULE_ERROR"
      });
      continue;
    }
    if (!result.conditionResult && condition.required) {
      const message = getLocalizedMessage(
        condition,
        null,
        locale,
        `Pre-condition '${result.ruleName || condition.ruleId}' failed`
      );
      errors.push({
        ruleId: condition.ruleId,
        message,
        code: "PRE_CONDITION_FAILED"
      });
    }
  }
  return {
    canStart: errors.length === 0,
    errors,
    validatedRules
  };
}
function getLocalizedMessage(condition, rule, locale, defaultMessage) {
  if (condition.validationMessage?.[locale]) {
    return condition.validationMessage[locale];
  }
  if (condition.validationMessage?.["en"]) {
    return condition.validationMessage["en"];
  }
  if (rule) {
    if (rule.failureActions && Array.isArray(rule.failureActions)) {
      const blockAction = rule.failureActions.find(
        (a) => a.type === "BLOCK_TRANSITION"
      );
      if (blockAction?.config?.message) {
        return blockAction.config.message;
      }
    }
    if (rule.description) {
      return rule.description;
    }
  }
  return defaultMessage;
}
export {
  validateWorkflowStart
};
//# sourceMappingURL=start-validator.js.map
