import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Nonzero cache price cannot silently round to free", WEB, async ({ t3, app, screen }) => {
  await t3.project("price-demo");
  await t3.open("/usage");
  const openPrices = async () => {
    await screen.getByRole("button", "All environments", { exact: true }).tap();
    await screen.getByRole("menuitem", "Model prices", { exact: true }).tap();
  };
  await openPrices();
  await screen.getByRole("button", "Add model price", { exact: true }).tap();
  await screen.getByRole("combobox", "New model ID", { exact: true }).fill("repro-model");
  await screen.getByRole("textbox", "Input price for repro-model", { exact: true }).fill("2");
  await screen.getByRole("textbox", "Output price for repro-model", { exact: true }).fill("1");
  const cache = screen.getByRole("textbox", "Cache read price for repro-model", { exact: true });
  const save = screen.getByRole("button", "Save changes", { exact: true });
  await cache.fill("1e-324");
  await app.screenshot("nonzero-underflow-validation");
  let validationFailure: unknown;
  try {
    await expect(save).toBeDisabled();
  } catch (error) {
    validationFailure = error;
    await save.tap();
    await screen.getByText("Saved", { exact: true }).waitFor();
    await screen.getByRole("button", "Close", { exact: true }).tap();
    await openPrices();
    await app.screenshot("underflow-saved-as-free");
  }
  for (const [entered, stored] of [["5e-324", "5e-324"], ["0e-324", "0"]]) {
    await cache.fill(entered);
    await save.tap();
    await screen.getByText("Saved", { exact: true }).waitFor();
    await screen.getByRole("button", "Close", { exact: true }).tap();
    await openPrices();
    await expect(cache).toHaveValue(stored);
    await app.screenshot(`control-${entered}`);
  }
  if (validationFailure) throw validationFailure;
});
