import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Question kinds appear only in the filter", WEB, async ({ t3, app, screen }) => {
  await t3.project("Workflow demo");
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.makeDirectory(`${T3_HOME}/workflows`, { recursive: true });
    yield* fs.writeFileString(`${T3_HOME}/workflows/review.ts`, `export default T3.workflow("review", {
      version: 1, payload: Schema.Struct({ kind: Schema.String }),
      asks: { feature: "Feature wanted?", intended: "Bug or intended?" }
    }, Effect.fn(function* (payload) {
      yield* T3.title(payload.kind === "feature" ? "Feature review" : "Behavior review");
      yield* T3.ask("decision", { kind: payload.kind, title: "Which way?", choices: ["Yes", "No"] });
    }));`);
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: { workflowsEnabled: true } });
  }).pipe(Effect.scoped));
  for (const kind of ["feature", "intended"]) {
    await runPromise(makeState(T3_HOME).cli(["workflow", "start", "review", "--key", kind, "--input", JSON.stringify({ kind }), "--json"]));
  }
  await t3.open("/workflows");
  await screen.getByRole("button", "Needs you", { exact: true }).tap();
  const picker = screen.getByRole("combobox", "Kind of question", { exact: true });
  await picker.waitFor();
  await screen.getByText("Feature review", { exact: true }).first().waitFor();
  await screen.getByText("Behavior review", { exact: true }).first().waitFor();
  await app.screenshot("all-kinds-waiting-runs");
  await picker.tap();
  await screen.getByRole("option", /Feature wanted/).waitFor();
  await app.screenshot("question-kind-dropdown");
  await screen.getByRole("option", /Feature wanted/).tap();
  await screen.getByText("Feature review", { exact: true }).first().waitFor();
  await app.screenshot("feature-kind-filtered");
  await picker.tap();
  await screen.getByRole("option", "All kinds", { exact: true }).tap();
  await screen.getByText("Behavior review", { exact: true }).first().waitFor();
  await app.screenshot("all-kinds-restored");
  await expect(screen.getByRole("list", "Questions by kind", { exact: true })).toBeHidden();
});
