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("Daily weekday summaries describe sets", WEB, async ({ t3, app, screen }) => {
  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 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, days] of [["everyDay", [6,5,4,3,2,1,0]], ["repeated", [3,1,1]]] as const) {
      yield* fs.writeFileString(path.join(dir, `${name}.ts`), `export default T3.workflow("${name}", { version: 1, payload: T3.Tick, triggers: [T3.daily("09:00", { weekdays: ${JSON.stringify(days)} })] }, () => Effect.void);`);
    }
  }));
  await t3.project("Workflow demo");
  await on(true);
  try {
    await t3.open("/workflows");
    const actual: string[] = [];
    for (const name of ["everyDay", "repeated"]) {
      await screen.getByRole("combobox", { name: "Workflow", exact: true }).click();
      await screen.getByRole("option", { name, exact: true }).click();
      const summary = screen.getByText(/^Starts on daily at 09:00/);
      await summary.waitFor();
      await app.screenshot(name);
      actual.push(await summary.textContent() ?? "");
    }
    expect(actual).toEqual(["Starts on daily at 09:00", "Starts on daily at 09:00 on Mon, Wed"]);
  } finally { await on(false); }
});
