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, useLocation } from "react-router-dom";
import { server } from "../test/server";
import { renderApp } from "../test/render";
import { ObjectNewPage } from "./object-new-page";

function EditStub() {
  const location = useLocation();
  const flagged = (location.state as { fieldsError?: boolean } | null)?.fieldsError === true;
  return <div>edit page{flagged ? " (fields error)" : ""}</div>;
}

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

test("create: POST then PUT fields, then navigate to the new object's detail", async () => {
  let postBody: unknown;
  let fieldsBody: unknown;

  server.use(
    http.post("/api/admin/objects", async ({ request }) => {
      postBody = await request.json();
      return HttpResponse.json({ id: "new-id-1" }, { status: 201 });
    }),
    http.put("/api/admin/objects/:id/fields", async ({ request }) => {
      fieldsBody = await request.json();
      return new HttpResponse(null, { status: 204 });
    }),
  );

  renderApp(tree(), { route: "/objects/new" });

  await userEvent.type(await screen.findByLabelText(/object number/i), "A-9");
  await userEvent.type(screen.getByLabelText(/^name/i), "Amphora");
  await userEvent.type(screen.getByLabelText(/inscription/i), "To the gods");
  await userEvent.click(screen.getByRole("button", { name: /create object/i }));

  await waitFor(() => expect(screen.getByText("detail view")).toBeInTheDocument());
  expect((postBody as { object_number: string }).object_number).toBe("A-9");
  expect((fieldsBody as { inscription: string }).inscription).toBe("To the gods");
});

test("partial create: fields PUT fails -> navigate to edit with an error banner", async () => {
  server.use(
    http.post("/api/admin/objects", () =>
      HttpResponse.json({ id: "new-id-2" }, { status: 201 }),
    ),
    http.put("/api/admin/objects/:id/fields", () =>
      new HttpResponse(null, { status: 422 }),
    ),
  );

  renderApp(tree(), { route: "/objects/new" });

  await userEvent.type(await screen.findByLabelText(/object number/i), "A-9");
  await userEvent.type(screen.getByLabelText(/^name/i), "Amphora");
  await userEvent.type(screen.getByLabelText(/inscription/i), "x");
  await userEvent.click(screen.getByRole("button", { name: /create object/i }));

  await waitFor(() => expect(screen.getByText(/edit page \(fields error\)/i)).toBeInTheDocument());
});
