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

const deliver = Effect.fn("scenario.deliver")(function* (origin: string) {
  const issued = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]);
  const { projects } = yield* HttpClient.execute(
    HttpClientRequest.get(`${origin}/api/projects`).pipe(HttpClientRequest.bearerToken(issued.stdout.trim())),
  ).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.flatMap(HttpClientResponse.schemaBodyJson(ProjectSnapshot)));
  const client = yield* rpcClient(T3_HOME, origin);
  const { task } = yield* client["scheduledTasks.upsert"]({
    title: "Null assignees repro", prompt: "Say hello. Assignees: {{body.issue.assignees[].login}}",
    enabled: true,
    schedule: { type: "webhook", filters: [{ path: "body.issue.assignees[].login", op: "notEquals", value: "bot" }] },
    projectId: projects.find((project) => project.title === "server")!.id,
    workspaceStrategy: { type: "root" },
    modelSelection: { instanceId: ProviderInstanceId.make("devReplay"), model: "showcase" },
    runtimeMode: "full-access", interactionMode: "default",
  });
  const outcomes = [];
  for (const body of [{issue:{assignees:[]}}, {issue:{}}, {issue:{assignees:null}}]) {
    const response = yield* HttpClient.execute(HttpClientRequest.post(`${origin}${task.webhook!.path}`).pipe(HttpClientRequest.bodyJsonUnsafe(body)));
    outcomes.push({status:response.status, outcome:response.headers["x-t3-hook-outcome"]});
  }
  return outcomes;
}, Effect.scoped, Effect.provide(FetchHttpClient.layer));

test("Null wildcard lists run like empty lists; absent keys remain filtered", WEB, async ({t3,app,screen}) => {
  await t3.project("server");
  const outcomes = await runPromise(deliver(app.baseUrl ?? ""));
  await t3.open("/settings/scheduled-tasks");
  await screen.getByRole("button", "Actions for Null assignees repro").tap();
  await screen.getByRole("menuitem", "Deliveries").tap();
  const dialog = screen.getByRole("dialog");
  await dialog.getByRole("button", /POST/).first().waitFor();
  await app.screenshot("delivery-outcomes");
  await dialog.getByRole("button", /POST/).first().tap();
  await dialog.getByText('{"issue":{"assignees":null}}', {exact:true}).waitFor();
  try {
    await expect(dialog.getByText("Ran", {exact:true})).toBeVisible();
    expect(outcomes).toEqual([{status:202,outcome:"accepted"},{status:202,outcome:"filtered"},{status:202,outcome:"accepted"}]);
    await expect(dialog.getByText(/Say hello\. Assignees: <webhook-data-[a-f0-9]+>\[\]<\/webhook-data-[a-f0-9]+>/)).toBeVisible();
  } finally {
    await app.screenshot("null-assignees-delivery");
  }
});
