import { expect, test } from "vitest";
import { screen, waitFor } 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 { ObjectEditForm } from "./object-edit-form";
import { amphora } from "../test/fixtures";

function tree() {
  return (
    <Routes>
      <Route path="/objects/:id/edit" element={<ObjectEditForm />} />
      <Route path="/objects/:id" element={<div>detail view</div>} />
    </Routes>
  );
}

test("edit: fields PUT 422 with type_mismatch code -> code-specific field message shown and field marked invalid", async () => {
  server.use(
    http.get("/api/admin/objects/:id", () =>
      HttpResponse.json({ ...amphora, fields: { inscription: "old" } }),
    ),
    http.put("/api/admin/objects/:id", () => new HttpResponse(null, { status: 204 })),
    http.put("/api/admin/objects/:id/fields", () =>
      HttpResponse.json({ field: "inscription", code: "type_mismatch" }, { status: 422 }),
    ),
  );

  renderApp(tree(), { route: `/objects/${amphora.id}/edit` });

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

  // Banner still reports the rejected field name; the field highlight uses the code-specific message.
  await screen.findByText(/inscription.*rejected/i);

  expect(await screen.findByText("Wrong type for this field")).toBeInTheDocument();
});

test("edit: prefilled, save -> PUT core + PUT fields -> back to detail", async () => {
  let putCore: unknown;
  let putFields: unknown;

  server.use(
    http.get("/api/admin/objects/:id", () =>
      HttpResponse.json({ ...amphora, fields: { inscription: "old" } }),
    ),
    http.put("/api/admin/objects/:id", async ({ request }) => {
      putCore = await request.json();
      return new HttpResponse(null, { status: 204 });
    }),
    http.put("/api/admin/objects/:id/fields", async ({ request }) => {
      putFields = await request.json();
      return new HttpResponse(null, { status: 204 });
    }),
  );

  renderApp(tree(), { route: `/objects/${amphora.id}/edit` });

  const name = await screen.findByDisplayValue("Amphora");

  await userEvent.clear(name);
  await userEvent.type(name, "Big amphora");
  await userEvent.click(screen.getByRole("button", { name: /save/i }));

  await waitFor(() => expect(screen.getByText("detail view")).toBeInTheDocument());
  expect((putCore as { object_name: string }).object_name).toBe("Big amphora");
  expect((putFields as { inscription: string }).inscription).toBe("old");
});

test("renders a load error (not 'not found') when the object fetch fails", async () => {
  server.use(http.get("/api/admin/objects/:id", () => new HttpResponse(null, { status: 500 })));
  renderApp(
    <Routes>
      <Route path="/objects/:id/edit" element={<ObjectEditForm />} />
    </Routes>,
    { route: "/objects/abc/edit" },
  );
  expect(await screen.findByText(/could not load/i)).toBeInTheDocument();
  expect(screen.queryByText(/not found/i)).toBeNull();
});
