import { Result, err, ok } from "neverthrow";

import { toQuestionIdentity } from "./question-identity";
import { TAnswerPresetSet, TConfigurationError } from "./types";

/**
 * Checks how a preset set wires its Dependent Answers, without touching the Survey. Returns `err`
 * with the first wiring mistake: a dependency key missing from the set, or one that runs at or
 * after its Dependent Answer.
 */
export function checkPresetSetWiring<TStorePreset>(
  presetSet: TAnswerPresetSet<TStorePreset>,
): Result<void, TConfigurationError> {
  // Positions follow the order the run visits questions in (`Object.entries`), not numeric key
  // order: fractional keys are visited after every integer key.
  const presetEntries = Object.entries(presetSet);
  const questionKeyToPosition = new Map(
    presetEntries.map(([questionKeyText], position) => [Number(questionKeyText), position]),
  );

  for (const [position, [questionKeyText, answerPreset]] of presetEntries.entries()) {
    if (answerPreset.answerDependency === "directAnswer") continue;

    const questionKey = Number(questionKeyText);
    const dependentQuestion = toQuestionIdentity(answerPreset);
    for (const dependencyKey of answerPreset.dependencyKeys) {
      const dependencyPosition = questionKeyToPosition.get(dependencyKey);
      if (dependencyPosition === undefined) {
        return err({
          kind: "missingDependency",
          message: `Dependent Answer ${questionKey} ('${String(dependentQuestion.questionLabel)}') depends on key ${dependencyKey}, which is not in its preset set`,
          questionKey,
          dependentQuestion,
          dependencyKey,
        });
      }
      if (dependencyPosition >= position) {
        return err({
          kind: "dependencyNotEarlier",
          message: `Dependent Answer ${questionKey} ('${String(dependentQuestion.questionLabel)}') depends on key ${dependencyKey}, which does not run before it`,
          questionKey,
          dependentQuestion,
          dependencyKey,
        });
      }
    }
  }

  return ok(undefined);
}
