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 { ObjectNewPage } from "./object-new-page";
import { ObjectEditForm } from "./object-edit-form";

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={<ObjectEditForm />} />
    </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 -> edit page shows the 'created' banner and highlights the field", async () => {
  // POST returns the amphora id so the default GET /api/admin/objects/:id handler
  // resolves and the real ObjectEditForm renders at /objects/:id/edit.
  server.use(
    http.post("/api/admin/objects", () =>
      HttpResponse.json({ id: "11111111-1111-1111-1111-111111111111" }, { status: 201 }),
    ),
    http.put("/api/admin/objects/:id/fields", () =>
      HttpResponse.json({ field: "inscription", code: "type_mismatch" }, { 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(/object created, but a field was rejected/i)).toBeInTheDocument(),
  );
  expect(await screen.findByText(/wrong type for this field/i)).toBeInTheDocument();
});

test("in-flight submit: button disabled + shows Saving…, create fires exactly once on double-click", async () => {
  let postCount = 0;
  let release!: () => void;
  const gate = new Promise<void>((resolve) => {
    release = resolve;
  });

  server.use(
    http.post("/api/admin/objects", async () => {
      postCount += 1;
      await gate;
      return HttpResponse.json({ id: "new-id-3" }, { status: 201 });
    }),
  );

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

  const button = screen.getByRole("button", { name: /create object/i });
  await userEvent.click(button);
  await userEvent.click(button);

  // The mutation is held open by `gate`, so the pending state is observed
  // deterministically (no reliance on a timing window).
  expect(await screen.findByText(/saving…/i)).toBeInTheDocument();
  expect(screen.getByRole("button", { name: /saving…/i })).toBeDisabled();

  release();

  await waitFor(() => expect(screen.getByText("detail view")).toBeInTheDocument());
  expect(postCount).toBe(1);
});

test("Save & create another: resets the form and stays on /objects/new", async () => {
  server.use(
    http.post("/api/admin/objects", () =>
      HttpResponse.json({ id: "new-id-4" }, { status: 201 }),
    ),
  );

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

  const numberInput = (await screen.findByLabelText(/object number/i)) as HTMLInputElement;
  await userEvent.type(numberInput, "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: /save & create another/i }));

  await waitFor(() => expect(numberInput.value).toBe(""));
  expect(screen.queryByText("detail view")).not.toBeInTheDocument();
  expect(screen.getByRole("button", { name: /save & create another/i })).toBeInTheDocument();
});
