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 field body -> field error 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 }));

  const alerts = await screen.findAllByText(/inscription.*rejected/i);
  expect(alerts.length).toBeGreaterThanOrEqual(2);
});

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");
});
