import { expect, test } from "vitest";
import { screen } from "@testing-library/react";
import { http, HttpResponse } from "msw";
import { Routes, Route } from "react-router-dom";
import { server } from "../test/server";
import { renderApp } from "../test/render";
import { ObjectDetail } from "./object-detail";

function tree() {
  return (
    <Routes>
      <Route path="/objects/:id" element={<ObjectDetail />} />
    </Routes>
  );
}

test("renders inventory-minimum fields, flexible values and visibility", async () => {
  // override so the object carries a flexible field value (schema types fields as
  // Record<string,never>, so return a plain object literal here)
  server.use(
    http.get("/api/admin/objects/:id", () =>
      HttpResponse.json({
        id: "11111111-1111-1111-1111-111111111111",
        object_number: "LM-0042",
        object_name: "Amphora",
        number_of_objects: 1,
        brief_description: "Storage jar",
        current_location: "Vault 3",
        current_owner: null,
        recorder: null,
        recording_date: null,
        visibility: "public",
        fields: { material: "Bronze" },
      }),
    ),
  );
  renderApp(tree(), { route: "/objects/11111111-1111-1111-1111-111111111111" });
  expect(await screen.findByText("Amphora")).toBeInTheDocument();
  expect(screen.getByText("Vault 3")).toBeInTheDocument();
  expect(screen.getByText("Bronze")).toBeInTheDocument(); // flexible field value
  // "Public" appears in both the VisibilityBadge and the PublishControl stepper;
  // scope the assertion to the badge element to avoid ambiguity.
  expect(document.querySelector("[data-slot='badge']")).toHaveTextContent("Public");
});

test("shows a not-found state for a missing object", async () => {
  server.use(http.get("/api/admin/objects/:id", () => new HttpResponse(null, { status: 404 })));
  renderApp(tree(), { route: "/objects/does-not-exist" });
  expect(await screen.findByText(/object not found/i)).toBeInTheDocument();
});

test("detail shows the publish control with the current visibility stepper", async () => {
  // default GET /api/admin/objects/:id handler returns amphora (visibility "public")
  renderApp(tree(), { route: "/objects/11111111-1111-1111-1111-111111111111" });
  expect(await screen.findByText(/visibility/i)).toBeInTheDocument();
  expect(await screen.findByRole("button", { name: /unpublish to internal/i })).toBeInTheDocument();
});
