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";

const DEFINITION = `export default T3.workflow("report", { version: 1, payload: Schema.Struct({ title: Schema.String }) }, Effect.fn(function* ({ title }) { yield* T3.title(title); }));`;

test("Reopening the workflow panel restores the selected older run", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("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/report.ts`, DEFINITION);
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: { workflowsEnabled: true } });
  }).pipe(Effect.scoped));
  const start = async (key: string, title: string) => {
    const result = await runPromise(makeState(T3_HOME).cli(["workflow", "start", "report", "--key", key, "--input", JSON.stringify({ title }), "--json"]));
    return JSON.parse(result.stdout).run.runId as string;
  };
  const first = await start("first", "First report");
  await t3.open(`/workflows?run=${first}`);
  await screen.getByRole("article", "First report", { exact: true }).waitFor();
  const second = await start("second", "Second report");
  await t3.open(`/workflows?run=${second}`);
  await screen.getByRole("article", "Second report", { exact: true }).waitFor();
  await screen.getByRole("button", /report.*First report/).tap();
  await screen.getByRole("article", "First report", { exact: true }).waitFor();
  await app.screenshot("selected-first-report");
  const toggle = screen.getByRole("button", "Toggle right panel", { exact: true });
  await toggle.tap();
  await app.screenshot("panel-hidden");
  await toggle.tap();
  await screen.getByRole("article").waitFor();
  await app.screenshot("panel-reopened");
  await expect(screen.getByRole("article")).toHaveAttribute("aria-label", "First report");
  expect(new URL(await browser.url()).searchParams.get("run")).toBe(first);
});
