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

import { TAutofillSurvey, runAutofill } from "../../autofill";
import { VITAL_FARMS_ANSWER_PRESETS } from "./answer-presets";
import { VITAL_FARMS_STORE_PRESETS } from "./store-presets";

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

function createInMemorySurvey(storeNumber: string) {
  const writes: TRecordedWrite[] = [];
  const survey: TAutofillSurvey = {
    getStoreNumber: () => storeNumber,
    answer: (method, questionLabel, value) => {
      writes.push({ method, questionLabel, value });
    },
    answerBySection: () => {
      throw new Error("Vital Farms questions have no section");
    },
  };
  return { survey, writes };
}

describe("Vital Farms Answer Presets", () => {
  it("skips the backstock questions a Store leaves out and fills the rest", async () => {
    vi.spyOn(console, "log").mockImplementation(() => {});
    const { survey, writes } = createInMemorySurvey("T1344");

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

    const runOutcome = result._unsafeUnwrap();
    expect(runOutcome.failed).toEqual([]);
    expect(runOutcome.filled).toHaveLength(13);
    expect(runOutcome.skipped.map((question) => question.questionLabel)).toEqual([
      "WHERE in the backroom is Egg backstock kept",
      "HOW are Eggs backstocked in your store",
    ]);
    expect(writes).toContainEqual({
      method: "input",
      questionLabel: "HOW MANY DAYS PER WEEK does the store receive DELIEVERIES for Eggs",
      value: "2",
    });
    expect(
      writes.filter((write) => write.method === "checkbox").map((write) => write.value),
    ).toEqual(["Tuesday", "Friday"]);
  });

  it("fills every question for a Store that configures them all", async () => {
    vi.spyOn(console, "log").mockImplementation(() => {});
    const { survey, writes } = createInMemorySurvey("T2451");

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

    const runOutcome = result._unsafeUnwrap();
    expect(runOutcome.filled).toHaveLength(15);
    expect(runOutcome.skipped).toEqual([]);
    expect(writes).toContainEqual({
      method: "radio",
      questionLabel: "WHERE in the backroom is Egg backstock kept",
      value: "Dairy Cooler",
    });
  });
});
