import { ProjectSnapshot, ProviderInstanceId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Scheduled labels describe unique days in weekday order", WEB, async ({ t3, app, screen }) => {
  await t3.project("Weekday label demo");
  await runPromise(Effect.gen(function* () {
    const issued = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]);
    const { projects } = yield* HttpClient.execute(HttpClientRequest.get(`${app.baseUrl}/api/projects`).pipe(HttpClientRequest.bearerToken(issued.stdout.trim()))).pipe(
      Effect.flatMap(HttpClientResponse.filterStatusOk),
      Effect.flatMap(HttpClientResponse.schemaBodyJson(ProjectSnapshot)),
    );
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    for (const [title, weekdays] of [["Repro A", [1,1,2,3,4]], ["Repro B", [0,1,2,3,4,5,6]], ["Repro C", [5,1,3]]] as const) {
      yield* client["scheduledTasks.upsert"]({
        title, prompt: "Report status", enabled: true,
        schedule: { type: "fixed_time", timeOfDay: "09:00", weekdays },
        projectId: projects.find(p => p.title === "Weekday label demo")!.id,
        workspaceStrategy: { type: "root" },
        modelSelection: { instanceId: ProviderInstanceId.make("devReplay"), model: "showcase" },
        runtimeMode: "full-access", interactionMode: "default",
      });
    }
  }).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer)));
  await t3.open("/settings/scheduled-tasks");
  await screen.getByRole("button", "Actions for Repro C").waitFor();
  try {
    await expect(screen.getByText(/Mon, Tue, Wed, Thu at/)).toBeVisible();
    await expect(screen.getByText(/Daily at/)).toBeVisible();
    await expect(screen.getByText(/Mon, Wed, Fri at/)).toBeVisible();
  } finally {
    await app.screenshot("scheduled-weekday-labels");
  }
});
