import { describe, expect, test, vi } from "vitest";
import { http, HttpResponse } from "msw";

import { server } from "../test/server";
import * as authRedirect from "./auth-redirect";
import { api } from "./client";

describe("api client", () => {
  test("returns typed data on success", async () => {
    server.use(
      http.get("/api/admin/me", () =>
        HttpResponse.json({ id: "u1", email: "a@b.se", role: "admin" }),
      ),
    );

    const { data, error } = await api.GET("/api/admin/me");

    expect(error).toBeUndefined();
    expect(data?.email).toBe("a@b.se");
  });

  test("a 401 triggers the auth redirect", async () => {
    const spy = vi.spyOn(authRedirect, "redirectToLogin").mockImplementation(() => {});

    server.use(http.get("/api/admin/me", () => new HttpResponse(null, { status: 401 })));

    await api.GET("/api/admin/me");

    expect(spy).toHaveBeenCalledOnce();

    spy.mockRestore();
  });
});
