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 { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Equivalent daily schedules are refused like identical schedules", WEB, async ({ t3, app, screen, browser }) => {
  const pairs = {
    "standup": 'T3.daily("3:58"), T3.daily("03:58")',
    "standup-weekdays": 'T3.daily("03:58", { weekdays: [4,1,1] }), T3.daily("03:58", { weekdays: [1,4] })',
    "standup-everyday": 'T3.daily("03:58"), T3.daily("03:58", { weekdays: [] })',
    "control-same-id": 'T3.daily("03:58"), T3.daily("03:58")',
  };
  const on = (enabled: boolean) => runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: { workflowsEnabled: enabled } });
  }).pipe(Effect.scoped));
  await t3.project("Schedule equivalence");
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    const path = yield* Path.Path;
    const dir = path.join(T3_HOME, "workflows");
    yield* fs.makeDirectory(dir, { recursive: true });
    for (const [name, triggers] of Object.entries(pairs)) {
      yield* fs.writeFileString(path.join(dir, `${name}.ts`), `export default T3.workflow("${name}", { version: 1, payload: T3.Tick, triggers: [${triggers}] }, () => Effect.void);\n`);
    }
  }));
    await on(true);
    await t3.open("/workflows?definitions=true");
    await screen.getByRole("button", "control-same-id.ts", { exact: false }).waitFor();
    // Mask the synthetic server directory; only the definition statuses are evidence.
    await browser.evaluate(() => {
      const style = document.createElement("style");
      style.textContent = "code { visibility: hidden !important; }";
      document.head.appendChild(style);
    });
    await app.screenshot("equivalent-daily-definitions");
    await expect(screen.getByText("Does not load", { exact: true })).toHaveCount(4);
});
