import { afterEach, describe, expect, it, vi } from "vitest";

import { getAfterOOSCount } from "../survey-runnables/beauty/util/utils";
import {
  TAutofillSurvey,
  TStoreNumber,
  assertAutofillSucceeded,
  runAutofill,
  setDependentAnswerPreset,
  setDirectAnswerPreset,
} from "./index";

type TRecordedWrite = {
  method: string;
  sectionName?: string | RegExp;
  questionLabel: string | RegExp;
  value: string;
};

// In-memory stand-in for the RMS Survey page: records every write, and throws on writes to any
// question label listed in `failingQuestionLabels`.
class InMemorySurvey implements TAutofillSurvey {
  readonly writes: TRecordedWrite[] = [];

  constructor(
    private readonly storeNumber: string,
    private readonly failingQuestionLabels: string[] = [],
  ) {}

  getStoreNumber(): string {
    return this.storeNumber;
  }

  answer(method: string, questionLabel: string | RegExp, value: string): void {
    this.record({ method, questionLabel, value });
  }

  answerBySection(
    method: string,
    sectionName: string | RegExp,
    questionLabel: string | RegExp,
    value: string,
  ): void {
    this.record({ method, sectionName, questionLabel, value });
  }

  private record(write: TRecordedWrite): void {
    if (this.failingQuestionLabels.includes(String(write.questionLabel))) {
      throw new Error(`No question element matched '${String(write.questionLabel)}'`);
    }
    this.writes.push(write);
  }
}

type TEggStorePreset = {
  service_day: string;
  delivery_days_per_week: number;
  delivery_days_of_week: string[];
  backstock_location?: string;
};

const EGG_STORE_PRESETS: Record<TStoreNumber, TEggStorePreset> = {
  T1344: {
    service_day: "Wednesday",
    delivery_days_per_week: 2,
    delivery_days_of_week: ["Tuesday", "Friday"],
  },
  T2451: {
    service_day: "Thursday",
    delivery_days_per_week: 1,
    delivery_days_of_week: ["Tuesday"],
    backstock_location: "Dairy Cooler",
  },
};

const EGG_ANSWER_PRESETS = {
  1: setDirectAnswerPreset(
    undefined,
    "What DAY OF THE WEEK",
    "radio",
    (storePreset: TEggStorePreset) => storePreset.service_day,
  ),
  2: setDirectAnswerPreset(
    "Deliveries",
    "HOW MANY DAYS PER WEEK",
    "text",
    (storePreset: TEggStorePreset) => storePreset.delivery_days_per_week,
  ),
};

describe("runAutofill", () => {
  it("writes Direct Answers with the current Store's preset values", async () => {
    const survey = new InMemorySurvey("T2451");

    const result = await runAutofill({
      survey,
      storePresets: EGG_STORE_PRESETS,
      presetSets: [EGG_ANSWER_PRESETS],
    });

    expect(result.isOk()).toBe(true);
    expect(survey.writes).toEqual([
      { method: "radio", questionLabel: "What DAY OF THE WEEK", value: "Thursday" },
      {
        method: "input",
        sectionName: "Deliveries",
        questionLabel: "HOW MANY DAYS PER WEEK",
        value: "1",
      },
    ]);
    expect(result._unsafeUnwrap().filled).toHaveLength(2);
  });

  it("leaves a Skipped Question when a Direct Answer returns null", async () => {
    const survey = new InMemorySurvey("T1344");
    const answerPresets = {
      1: setDirectAnswerPreset(
        undefined,
        "WHERE in the backroom",
        "radio",
        (storePreset: TEggStorePreset) => storePreset.backstock_location ?? null,
      ),
    };

    const result = await runAutofill({
      survey,
      storePresets: EGG_STORE_PRESETS,
      presetSets: [answerPresets],
    });

    expect(survey.writes).toEqual([]);
    const runOutcome = result._unsafeUnwrap();
    expect(runOutcome.skipped).toEqual([
      expect.objectContaining({ questionLabel: "WHERE in the backroom" }),
    ]);
    expect(runOutcome.filled).toEqual([]);
    expect(runOutcome.failed).toEqual([]);
  });

  it("records a failed question with its cause when a preset throws, and keeps going", async () => {
    const survey = new InMemorySurvey("T1344");
    const presetError = new Error("preset bug");
    const answerPresets = {
      1: setDirectAnswerPreset(undefined, "Buggy question", "text", (): number => {
        throw presetError;
      }),
      2: setDirectAnswerPreset(
        undefined,
        "What DAY OF THE WEEK",
        "radio",
        (storePreset: TEggStorePreset) => storePreset.service_day,
      ),
    };

    const result = await runAutofill({
      survey,
      storePresets: EGG_STORE_PRESETS,
      presetSets: [answerPresets],
    });

    const runOutcome = result._unsafeUnwrap();
    expect(runOutcome.failed).toEqual([
      expect.objectContaining({ questionLabel: "Buggy question", cause: presetError }),
    ]);
    expect(survey.writes).toEqual([
      { method: "radio", questionLabel: "What DAY OF THE WEEK", value: "Wednesday" },
    ]);
    expect(runOutcome.filled).toEqual([
      expect.objectContaining({ questionLabel: "What DAY OF THE WEEK" }),
    ]);
  });

  it("records a failed question when the Survey write throws, and keeps going", async () => {
    const survey = new InMemorySurvey("T1344", ["What DAY OF THE WEEK"]);

    const result = await runAutofill({
      survey,
      storePresets: EGG_STORE_PRESETS,
      presetSets: [EGG_ANSWER_PRESETS],
    });

    const runOutcome = result._unsafeUnwrap();
    expect(runOutcome.failed).toEqual([
      expect.objectContaining({
        questionLabel: "What DAY OF THE WEEK",
        cause: expect.objectContaining({ message: expect.stringMatching(/No question element/) }),
      }),
    ]);
    expect(survey.writes).toEqual([
      {
        method: "input",
        sectionName: "Deliveries",
        questionLabel: "HOW MANY DAYS PER WEEK",
        value: "2",
      },
    ]);
  });

  it("returns a configuration error naming the Store Number, with no writes, for an unknown Store", async () => {
    const survey = new InMemorySurvey("T9999");

    const result = await runAutofill({
      survey,
      storePresets: EGG_STORE_PRESETS,
      presetSets: [EGG_ANSWER_PRESETS],
    });

    expect(result.isErr()).toBe(true);
    const configurationError = result._unsafeUnwrapErr();
    expect(configurationError).toMatchObject({ kind: "unknownStore", storeNumber: "T9999" });
    expect(configurationError.message).toMatch(/T9999/);
    expect(survey.writes).toEqual([]);
  });

  it("writes each choice of a checkbox list", async () => {
    const survey = new InMemorySurvey("T1344");
    const answerPresets = {
      1: setDirectAnswerPreset(
        undefined,
        "What DAYS OF THE WEEK",
        "checkbox",
        (storePreset: TEggStorePreset) => storePreset.delivery_days_of_week,
      ),
    };

    const result = await runAutofill({
      survey,
      storePresets: EGG_STORE_PRESETS,
      presetSets: [answerPresets],
    });

    expect(survey.writes).toEqual([
      { method: "checkbox", questionLabel: "What DAYS OF THE WEEK", value: "Tuesday" },
      { method: "checkbox", questionLabel: "What DAYS OF THE WEEK", value: "Friday" },
    ]);
    expect(result._unsafeUnwrap().filled).toEqual([{ questionLabel: "What DAYS OF THE WEEK" }]);
  });

  describe("Dependent Answers", () => {
    it("receive the values computed for their dependencies, in dependency-array order", async () => {
      const survey = new InMemorySurvey("T1344");
      const receivedDependencyAnswers: string[][] = [];
      const answerPresets = {
        1: setDirectAnswerPreset(undefined, "Before count", "text", () => 7),
        2: setDirectAnswerPreset(undefined, "Day", "radio", () => "Monday"),
        3: setDependentAnswerPreset(undefined, "Summary", "text", [2, 1], (dependencyAnswers) => {
          receivedDependencyAnswers.push(dependencyAnswers);
          return `${dependencyAnswers[0]}:${dependencyAnswers[1]}`;
        }),
      };

      const result = await runAutofill({
        survey,
        storePresets: EGG_STORE_PRESETS,
        presetSets: [answerPresets],
      });

      expect(receivedDependencyAnswers).toEqual([["Monday", "7"]]);
      expect(survey.writes.at(-1)).toEqual({
        method: "input",
        questionLabel: "Summary",
        value: "Monday:7",
      });
      expect(result._unsafeUnwrap().filled).toHaveLength(3);
    });

    it("are bounded by their dependency: the After count never exceeds the Before count", async () => {
      for (const beforeCount of [0, 1, 3, 4, 10]) {
        const survey = new InMemorySurvey("T1344");
        const answerPresets = {
          10: setDirectAnswerPreset(undefined, "Before count", "text", () => beforeCount),
          30: setDependentAnswerPreset(undefined, "After count", "text", [10], getAfterOOSCount),
        };

        await runAutofill({ survey, storePresets: EGG_STORE_PRESETS, presetSets: [answerPresets] });

        const afterCountWrite = survey.writes.find(
          (write) => write.questionLabel === "After count",
        );
        const afterCount = Number(afterCountWrite?.value);
        expect(afterCount).toBeGreaterThanOrEqual(0);
        expect(afterCount).toBeLessThanOrEqual(beforeCount);
      }
    });

    it("are skipped, directly and transitively, when a dependency is skipped", async () => {
      const survey = new InMemorySurvey("T1344");
      const answerPresets = {
        1: setDirectAnswerPreset(undefined, "Backroom location", "radio", () => null),
        2: setDependentAnswerPreset(undefined, "Backroom count", "text", [1], () => 4),
        3: setDependentAnswerPreset(undefined, "Backroom note", "text", [2], () => "note"),
      };

      const result = await runAutofill({
        survey,
        storePresets: EGG_STORE_PRESETS,
        presetSets: [answerPresets],
      });

      expect(survey.writes).toEqual([]);
      const runOutcome = result._unsafeUnwrap();
      expect(runOutcome.skipped).toEqual([
        { questionLabel: "Backroom location" },
        { questionLabel: "Backroom count" },
        { questionLabel: "Backroom note" },
      ]);
      expect(runOutcome.blocked).toEqual([]);
      expect(runOutcome.failed).toEqual([]);
    });

    it("are blocked, directly and transitively, naming the failed question, when a dependency fails", async () => {
      const consoleWarnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
      const survey = new InMemorySurvey("T1344", ["Before count"]);
      const answerPresets = {
        1: setDirectAnswerPreset("Essie", "Before count", "text", () => 7),
        2: setDependentAnswerPreset("Essie", "After count", "text", [1], getAfterOOSCount),
        3: setDependentAnswerPreset(undefined, "Inaccurate counts", "text", [2], () => 1),
        4: setDirectAnswerPreset(undefined, "Stocked count", "text", () => 12),
      };

      const result = await runAutofill({
        survey,
        storePresets: EGG_STORE_PRESETS,
        presetSets: [answerPresets],
      });

      const runOutcome = result._unsafeUnwrap();
      const failedQuestion = { sectionName: "Essie", questionLabel: "Before count" };
      expect(runOutcome.failed).toEqual([expect.objectContaining(failedQuestion)]);
      expect(runOutcome.blocked).toEqual([
        { sectionName: "Essie", questionLabel: "After count", failedDependency: failedQuestion },
        { questionLabel: "Inaccurate counts", failedDependency: failedQuestion },
      ]);
      expect(survey.writes).toEqual([
        { method: "input", questionLabel: "Stocked count", value: "12" },
      ]);
      expect(runOutcome.filled).toEqual([{ questionLabel: "Stocked count" }]);

      const warnLogText = consoleWarnSpy.mock.calls.flat().map(String).join(" ");
      expect(warnLogText).toMatch(/Inaccurate counts.*Before count/);
      consoleWarnSpy.mockRestore();
    });

    it("are blocked rather than skipped when one dependency failed and another was skipped", async () => {
      const answerPresets = {
        1: setDirectAnswerPreset(undefined, "Skipped", "text", () => null),
        2: setDirectAnswerPreset(undefined, "Failing", "text", (): number => {
          throw new Error("preset bug");
        }),
        3: setDependentAnswerPreset(undefined, "Total", "text", [1, 2], () => 0),
      };

      const result = await runAutofill({
        survey: new InMemorySurvey("T1344"),
        storePresets: EGG_STORE_PRESETS,
        presetSets: [answerPresets],
      });

      expect(result._unsafeUnwrap().blocked).toEqual([
        { questionLabel: "Total", failedDependency: { questionLabel: "Failing" } },
      ]);
    });
  });

  describe("dependency-wiring checks", () => {
    it("return a configuration error naming the Dependent Answer and the missing key, with no writes", async () => {
      const survey = new InMemorySurvey("T1344");
      const answerPresets = {
        7: setDirectAnswerPreset(undefined, "Garnier before", "text", () => 4),
        8: setDependentAnswerPreset(undefined, "Garnier after", "text", [6], () => 1),
      };

      const result = await runAutofill({
        survey,
        storePresets: EGG_STORE_PRESETS,
        presetSets: [answerPresets],
      });

      expect(survey.writes).toEqual([]);
      const configurationError = result._unsafeUnwrapErr();
      expect(configurationError).toMatchObject({
        kind: "missingDependency",
        dependentQuestion: { questionLabel: "Garnier after" },
        dependencyKey: 6,
      });
      expect(configurationError.message).toMatch(/Garnier after/);
      expect(configurationError.message).toMatch(/\b6\b/);
    });

    it.each([
      { case: "after it", dependencyKey: 9 },
      { case: "on itself", dependencyKey: 8 },
    ])(
      "return a configuration error, with no writes, for a dependency $case",
      async ({ dependencyKey }) => {
        const survey = new InMemorySurvey("T1344");
        const answerPresets = {
          7: setDirectAnswerPreset(undefined, "Garnier before", "text", () => 4),
          8: setDependentAnswerPreset(
            undefined,
            "Garnier after",
            "text",
            [7, dependencyKey],
            () => 1,
          ),
          9: setDirectAnswerPreset(undefined, "Garnier counts corrected", "text", () => 0),
        };

        const result = await runAutofill({
          survey,
          storePresets: EGG_STORE_PRESETS,
          presetSets: [answerPresets],
        });

        expect(survey.writes).toEqual([]);
        expect(result._unsafeUnwrapErr()).toMatchObject({
          kind: "dependencyNotEarlier",
          dependentQuestion: { questionLabel: "Garnier after" },
          dependencyKey,
        });
      },
    );

    // `Object.entries` visits 7.5 after every integer key, so it runs after 8 despite sitting
    // between 7 and 8 in the source.
    it("catch a fractional key written between integer keys that its dependent precedes", async () => {
      const survey = new InMemorySurvey("T1344");
      const answerPresets = {
        7: setDirectAnswerPreset(undefined, "Garnier before", "text", () => 4),
        7.5: setDirectAnswerPreset(undefined, "Garnier visual OOS", "text", () => 2),
        8: setDependentAnswerPreset(undefined, "Garnier after", "text", [7.5], () => 1),
      };

      const result = await runAutofill({
        survey,
        storePresets: EGG_STORE_PRESETS,
        presetSets: [answerPresets],
      });

      expect(survey.writes).toEqual([]);
      expect(result._unsafeUnwrapErr()).toMatchObject({
        kind: "dependencyNotEarlier",
        questionKey: 8,
        dependencyKey: 7.5,
      });
    });

    it("accept a fractional dependency that runs before its dependent", async () => {
      const survey = new InMemorySurvey("T1344");
      const answerPresets = {
        7: setDirectAnswerPreset(undefined, "Garnier before", "text", () => 4),
        7.5: setDirectAnswerPreset(undefined, "Garnier visual OOS", "text", () => 2),
        7.6: setDependentAnswerPreset(
          undefined,
          "Garnier visual OOS corrected",
          "text",
          [7, 7.5],
          (dependencyAnswers) => dependencyAnswers.join("/"),
        ),
      };

      const result = await runAutofill({
        survey,
        storePresets: EGG_STORE_PRESETS,
        presetSets: [answerPresets],
      });

      expect(result.isOk()).toBe(true);
      expect(survey.writes.at(-1)).toMatchObject({
        questionLabel: "Garnier visual OOS corrected",
        value: "4/2",
      });
    });
  });

  describe("several preset sets", () => {
    it("run as one combined outcome, with numeric keys resolved within their own set", async () => {
      const survey = new InMemorySurvey("T1344", ["Essie before"]);
      const essieAnswerPresets = {
        10: setDirectAnswerPreset(undefined, "Essie before", "text", () => 5),
        30: setDependentAnswerPreset(undefined, "Essie after", "text", [10], () => 2),
      };
      const maybellineAnswerPresets = {
        10: setDirectAnswerPreset(undefined, "Maybelline before", "text", () => 9),
        30: setDependentAnswerPreset(
          undefined,
          "Maybelline after",
          "text",
          [10],
          (dependencyAnswers) => dependencyAnswers[0],
        ),
      };

      const result = await runAutofill({
        survey,
        storePresets: EGG_STORE_PRESETS,
        presetSets: [essieAnswerPresets, maybellineAnswerPresets],
      });

      expect(survey.writes).toEqual([
        { method: "input", questionLabel: "Maybelline before", value: "9" },
        { method: "input", questionLabel: "Maybelline after", value: "9" },
      ]);
      const runOutcome = result._unsafeUnwrap();
      expect(runOutcome.filled).toEqual([
        { questionLabel: "Maybelline before" },
        { questionLabel: "Maybelline after" },
      ]);
      expect(runOutcome.failed).toEqual([
        expect.objectContaining({ questionLabel: "Essie before" }),
      ]);
      expect(runOutcome.blocked).toEqual([
        { questionLabel: "Essie after", failedDependency: { questionLabel: "Essie before" } },
      ]);
    });
  });

  describe("logging", () => {
    afterEach(() => {
      vi.restoreAllMocks();
    });

    it("logs failed questions as errors, skipped ones normally, and one summary line", async () => {
      const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
      const consoleLogSpy = vi.spyOn(console, "log").mockImplementation(() => {});
      const survey = new InMemorySurvey("T1344", ["What DAY OF THE WEEK"]);
      const answerPresets = {
        ...EGG_ANSWER_PRESETS,
        3: setDirectAnswerPreset(
          undefined,
          "WHERE in the backroom",
          "radio",
          (storePreset: TEggStorePreset) => storePreset.backstock_location ?? null,
        ),
      };

      await runAutofill({ survey, storePresets: EGG_STORE_PRESETS, presetSets: [answerPresets] });

      const errorLogText = consoleErrorSpy.mock.calls.flat().map(String).join(" ");
      expect(errorLogText).toMatch(/What DAY OF THE WEEK/);
      expect(errorLogText).toMatch(/No question element/);

      const logLines = consoleLogSpy.mock.calls.map((logArgs) => logArgs.map(String).join(" "));
      expect(logLines.some((logLine) => /WHERE in the backroom/.test(logLine))).toBe(true);
      expect(logLines.at(-1)).toMatch(/1 filled.*1 skipped.*0 blocked.*1 failed/);
    });
  });
});

describe("assertAutofillSucceeded", () => {
  it("throws naming the Store Number on a configuration error", async () => {
    const result = await runAutofill({
      survey: new InMemorySurvey("T9999"),
      storePresets: EGG_STORE_PRESETS,
      presetSets: [EGG_ANSWER_PRESETS],
    });

    expect(() => assertAutofillSucceeded(result)).toThrow(/T9999/);
  });

  it("throws naming the failed question when any question failed", async () => {
    const result = await runAutofill({
      survey: new InMemorySurvey("T1344", ["What DAY OF THE WEEK"]),
      storePresets: EGG_STORE_PRESETS,
      presetSets: [EGG_ANSWER_PRESETS],
    });

    expect(() => assertAutofillSucceeded(result)).toThrow(/What DAY OF THE WEEK/);
  });

  it("does not throw when questions were only filled or skipped", async () => {
    const answerPresets = {
      ...EGG_ANSWER_PRESETS,
      3: setDirectAnswerPreset(undefined, "WHERE in the backroom", "radio", () => null),
    };
    const result = await runAutofill({
      survey: new InMemorySurvey("T1344"),
      storePresets: EGG_STORE_PRESETS,
      presetSets: [answerPresets],
    });

    expect(() => assertAutofillSucceeded(result)).not.toThrow();
  });
});
