import { expect } from "e2e";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as Net from "@t3tools/shared/Net";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { GlobalFlag } from "effect/cli";
import { withThreadTools } from "../../apps/server/src/cli/thread.ts";
import { T3_HOME } from "../e2e.config.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Trailing CSS comments publish while a real import remains refused", WEB, async ({ t3, app, screen }) => {
  await t3.project("Theme publishing");
  const results = await runPromise(withThreadTools({ baseDir: Option.some(T3_HOME), json: true }, tools => Effect.gen(function* () {
    const cases = [
      ["scout-trailing-comment", "Trailing comment", ".a{color:red} /* documentation: url(https://example.invalid/logo.png)"],
      ["scout-trailing-import", "Trailing import", '.a{color:red} /* @import "x.css";'],
      ["scout-control", "Real import control", '@import "x.css"; /* trailing'],
      ["scout-closed-comment", "Closed comment", ".a{color:red} /* documentation: url(https://example.invalid/logo.png) */"],
    ];
    const outcomes = [];
    for (const [themeId, name, css] of cases) {
      outcomes.push(yield* tools.call("t3_theme_set", { themeId, theme: { name, appearance: "dark", canvas: "#1a1b26", accent: "#7aa2f7", css } }, Schema.Unknown).pipe(Effect.match({ onFailure: error => ({ themeId, refused: true, detail: String(error) }), onSuccess: value => ({ themeId, refused: false, value }) })));
    }
    return outcomes;
  })).pipe(Effect.provideService(GlobalFlag.LogLevel, "Error"), Effect.provide(Net.layer), Effect.provide(NodeCrypto.layer)));
  await t3.open("/settings/appearance");
  await screen.getByRole("button", "Use Closed comment theme", { exact: true }).waitFor();
  await screen.getByRole("button", "Use Closed comment theme", { exact: true }).scrollIntoView();
  await app.screenshot("published-themes-after-four-mcp-calls");
  expect(results.map(result => result.refused)).toEqual([false, false, true, false]);
  await expect(screen.getByRole("button", "Use Trailing comment theme", { exact: true })).toBeVisible();
  await expect(screen.getByRole("button", "Use Trailing import theme", { exact: true })).toBeVisible();
});
