import { expect, test } from "vitest";
import { screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { http, HttpResponse } from "msw";
import { Routes, Route } from "react-router-dom";
import { server } from "../test/server";
import { renderApp } from "../test/render";
import { DeleteObjectDialog } from "./delete-object-dialog";

function tree() {
  return (
    <Routes>
      <Route path="/objects/:id" element={<DeleteObjectDialog id="o-1" />} />
      <Route path="/objects" element={<div>objects list</div>} />
    </Routes>
  );
}

test("confirm delete: DELETE then navigate to the list", async () => {
  let deleted = false;

  server.use(
    http.delete("/api/admin/objects/:id", () => {
      deleted = true;
      return new HttpResponse(null, { status: 204 });
    }),
  );

  renderApp(tree(), { route: "/objects/o-1" });

  // open the dialog via the trigger
  await userEvent.click(await screen.findByRole("button", { name: /delete/i }));

  // confirm inside the dialog
  const dialog = await screen.findByRole("alertdialog");

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

  await waitFor(() => expect(screen.getByText("objects list")).toBeInTheDocument());

  expect(deleted).toBe(true);
});

test("cancel does not delete", async () => {
  let deleted = false;

  server.use(
    http.delete("/api/admin/objects/:id", () => {
      deleted = true;
      return new HttpResponse(null, { status: 204 });
    }),
  );

  renderApp(tree(), { route: "/objects/o-1" });

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

  const dialog = await screen.findByRole("alertdialog");

  await userEvent.click(within(dialog).getByRole("button", { name: /cancel/i }));

  expect(deleted).toBe(false);
  expect(screen.queryByText("objects list")).not.toBeInTheDocument();
});
