/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("OpenCode models can be found by ID after unfavoriting", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "Model ID search", messages: ["hello"] });
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: {}, providerInstanceMutation: {
      operation: "upsert", instanceId: ProviderInstanceId.make("opencode"),
      instance: { driver: ProviderDriverKind.make("opencode"), displayName: "OpenCode", enabled: true, config: {} },
    }});
  }).pipe(Effect.scoped));
  await t3.open(thread);
  await browser.locator('[data-chat-provider-model-picker="true"]').first().click();
  await browser.locator('[data-model-picker-provider="opencode"] button').first().click();
  const search = screen.getByPlaceholder("Search models...");
  await search.fill("DeepSeek V4.1 Flash");
  await screen.getByRole("option", /DeepSeek V4.1 Flash Free/).waitFor({ timeout: 60000 });
  const row = screen.getByRole("option", /DeepSeek V4.1 Flash Free/);
  await row.getByRole("button", "Add to favorites", { exact: true }).tap();
  await row.getByRole("button", "Remove from favorites", { exact: true }).tap();
  await app.screenshot("display-name-search");
  const found: boolean[] = [];
  for (const [query, label] of [
    ["opencode/deepseek-v4.1-flash-free", "full-model-id-search"],
    ["deepseek-v4.1-flash-free", "short-model-id-search"],
  ]) {
    await search.fill(query);
    // Wait for either real search outcome before capturing it.
    await expect.poll(() => browser.evaluate(() => {
      const picker = document.querySelector('[data-model-picker-content]');
      return Boolean(picker?.querySelector('[role="option"]')) || Boolean(picker?.textContent?.includes("No models found"));
    })).toBe(true);
    found.push(await row.isVisible());
    await app.screenshot(label);
  }
  expect(found).toEqual([true, true]);
});
