import { expect, test, vi } from "vitest";
import { screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

import { renderApp } from "../test/render";
import { DeleteConfirmDialog } from "./delete-confirm-dialog";
import { InUseError } from "../api/errors";

test("delete-in-use shows the in-use count and keeps the dialog open", async () => {
  const onConfirm = vi.fn(() => Promise.reject(new InUseError(3)));
  renderApp(<DeleteConfirmDialog description="Delete this term?" onConfirm={onConfirm} />);

  await userEvent.click(screen.getByRole("button", { name: /delete/i }));

  const dialog = within(document.body);
  const buttons = await dialog.findAllByRole("button", { name: /delete/i });
  await userEvent.click(buttons[buttons.length - 1]);

  expect(await dialog.findByText(/used by 3/i)).toBeInTheDocument();
  expect(dialog.getByText("Delete this term?")).toBeInTheDocument();
});

test("a clean confirm closes the dialog", async () => {
  const onConfirm = vi.fn(() => Promise.resolve());
  renderApp(<DeleteConfirmDialog description="Delete this term?" onConfirm={onConfirm} />);

  await userEvent.click(screen.getByRole("button", { name: /delete/i }));

  const dialog = within(document.body);
  const buttons = await dialog.findAllByRole("button", { name: /delete/i });
  await userEvent.click(buttons[buttons.length - 1]);

  await waitFor(() => expect(dialog.queryByText("Delete this term?")).toBeNull());
  expect(onConfirm).toHaveBeenCalledTimes(1);
});
