import { expect, test } from "vitest";
import { screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { http, HttpResponse } from "msw";

import type { TermView } from "../test/fixtures";
import { server } from "../test/server";
import { renderApp } from "../test/render";
import { TermRow } from "./term-row";

const term: TermView = {
  id: "t1",
  external_uri: null,
  labels: [{ lang: "en", label: "Bronze" }],
};

test("a failed term update shows an inline error and keeps the row editable", async () => {
  server.use(
    http.patch("/api/admin/vocabularies/:id/terms/:term_id", () => new HttpResponse(null, { status: 403 })),
  );
  renderApp(
    <ul>
      <TermRow vocabularyId="v1" term={term} lang="en" />
    </ul>,
  );

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

  expect(await screen.findByRole("alert")).toHaveTextContent(/permission/i);
  expect(screen.getByRole("button", { name: /save/i })).toBeInTheDocument();
});

test("re-entering edit after a failure clears the stale error", async () => {
  server.use(
    http.patch("/api/admin/vocabularies/:id/terms/:term_id", () => new HttpResponse(null, { status: 403 })),
  );
  renderApp(
    <ul>
      <TermRow vocabularyId="v1" term={term} lang="en" />
    </ul>,
  );

  await userEvent.click(screen.getByRole("button", { name: /edit/i }));
  await userEvent.click(screen.getByRole("button", { name: /save/i }));
  expect(await screen.findByRole("alert")).toBeInTheDocument();
  await userEvent.click(screen.getByRole("button", { name: /cancel/i }));
  await userEvent.click(screen.getByRole("button", { name: /edit/i }));

  expect(screen.queryByRole("alert")).toBeNull();
});
