import { http, HttpResponse } from "msw";

import { amphora, fibula, fieldDefinitions, materialTerms, objectsPage, personAuthorities, searchHits, vocabularies } from "./fixtures";

export const handlers = [
  http.get("/api/config", () =>
    HttpResponse.json({
      app_name: "Test Museum",
      default_language: "sv",
      default_timezone: "Europe/Stockholm",
    }),
  ),

  http.get("/api/admin/me", () =>
    HttpResponse.json({ id: "u1", email: "editor@example.com", role: "editor" }),
  ),

  http.get("/api/admin/objects", () => HttpResponse.json(objectsPage)),

  http.get("/api/admin/objects/:id", ({ params }) => {
    const found = [amphora, fibula].find((o) => o.id === params.id);

    return found ? HttpResponse.json(found) : new HttpResponse(null, { status: 404 });
  }),

  http.get("/api/admin/field-definitions", () => HttpResponse.json(fieldDefinitions)),

  http.get("/api/admin/vocabularies", () => HttpResponse.json(vocabularies)),

  http.get("/api/admin/vocabularies/:id/terms", () => HttpResponse.json(materialTerms)),

  http.get("/api/admin/authorities", ({ request }) => {
    const kind = new URL(request.url).searchParams.get("kind");

    return HttpResponse.json(kind === "person" ? personAuthorities : []);
  }),

  http.post("/api/admin/vocabularies", () =>
    HttpResponse.json({ id: "v-new", key: "new" }, { status: 201 }),
  ),

  http.post("/api/admin/vocabularies/:id/terms", () =>
    HttpResponse.json({ id: "t-new" }, { status: 201 }),
  ),

  http.post("/api/admin/authorities", () =>
    HttpResponse.json({ id: "a-new" }, { status: 201 }),
  ),

  http.post("/api/admin/objects", () =>
    HttpResponse.json({ id: "11111111-1111-1111-1111-111111111111" }, { status: 201 }),
  ),

  http.put("/api/admin/objects/:id", () => new HttpResponse(null, { status: 204 })),

  http.put("/api/admin/objects/:id/fields", () => new HttpResponse(null, { status: 204 })),

  http.delete("/api/admin/objects/:id", () => new HttpResponse(null, { status: 204 })),

  http.get("/api/admin/search", ({ request }) => {
    const url = new URL(request.url);
    const q = (url.searchParams.get("q") ?? "").trim();
    const offset = Number(url.searchParams.get("offset") ?? 0);
    const limit = Number(url.searchParams.get("limit") ?? 20);

    if (!q) return HttpResponse.json({ hits: [], estimated_total: 0 });

    return HttpResponse.json({
      hits: searchHits.slice(offset, offset + limit),
      estimated_total: searchHits.length,
    });
  }),

  http.post("/api/admin/login", () => new HttpResponse(null, { status: 204 })),

  http.post("/api/admin/logout", () => new HttpResponse(null, { status: 204 })),

  http.post("/api/admin/objects/:id/visibility", () => new HttpResponse(null, { status: 204 })),

  http.post("/api/admin/field-definitions", () =>
    HttpResponse.json({ key: "new_field" }, { status: 201 }),
  ),
];
