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

const DEFINITION = `export default T3.workflow("long-url-subject", { version: 1, payload: Schema.Struct({ n: Schema.Number }) }, Effect.fn(function* (payload) { yield* T3.subject('https://example.com/?q=' + 'x'.repeat(payload.n)); }));`;

test("Long workflow URL opens beside the run and survives reload", WEB, async ({t3, app, browser, screen}) => {
  const definition = await runPromise(Effect.map(Path.Path, path => path.join(T3_HOME, "workflows/longurl.ts")));
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.makeDirectory((yield* Path.Path).dirname(definition), {recursive:true});
    yield* fs.writeFileString(definition, DEFINITION);
  }));
  await t3.project("demo");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({patch:{workflowsEnabled:true}});
  }).pipe(Effect.scoped));
  for (const n of [100,400]) {
    const started = await runPromise(makeState(T3_HOME).cli(["workflow", "start", "long-url-subject", "--key", `length-${n}`, "--input", JSON.stringify({n}), "--json"]));
    const {run} = JSON.parse(started.stdout);
    await t3.open(`/workflows?run=${run.runId}`);
    const chip = screen.getByRole("article").getByRole("button", "example.com", {exact:true});
    await chip.waitFor({timeout:30000});
    await chip.tap();
    const link = screen.getByRole("link", "Open", {exact:true});
    if (n === 100) await expect(link).toHaveAttribute("href", "https://example.com/?q=" + "x".repeat(n));
    await app.screenshot(`url-${n}-after-click`);
    await expect(link).toHaveAttribute("href", "https://example.com/?q=" + "x".repeat(n));
    await browser.reload();
    await chip.waitFor({timeout:30000});
    await expect(link).toHaveAttribute("href", "https://example.com/?q=" + "x".repeat(n));
    await app.screenshot(`url-${n}-after-reload`);
  }
});
