import { describe, it, expect, vi, beforeEach } from "vitest";
import * as client from "./client";
import { fetchTeams, createTeam, fetchTeamMembers, updateTeam, deleteTeam } from "./teams";

vi.mock("./client");

const localStorageMock = {
  getItem: vi.fn().mockReturnValue("ws-1"),
  setItem: vi.fn(),
  clear: vi.fn(),
  removeItem: vi.fn(),
  length: 0,
  key: vi.fn(),
};
Object.defineProperty(window, "localStorage", { value: localStorageMock });

beforeEach((): void => {
  vi.clearAllMocks();
  localStorageMock.getItem.mockReturnValue("ws-1");
});

describe("fetchTeams", (): void => {
  it("calls teams endpoint for active workspace", async (): Promise<void> => {
    vi.mocked(client.apiGet).mockResolvedValueOnce([] as never);
    await fetchTeams();
    expect(client.apiGet).toHaveBeenCalledWith("/api/workspaces/ws-1/teams", "ws-1");
  });

  it("throws if no workspace id in localStorage", async (): Promise<void> => {
    localStorageMock.getItem.mockReturnValue(null);
    await expect(fetchTeams()).rejects.toThrow();
  });
});

describe("createTeam", (): void => {
  it("posts to teams endpoint", async (): Promise<void> => {
    vi.mocked(client.apiPost).mockResolvedValueOnce({ id: "t1", name: "Dev" } as never);
    await createTeam({ name: "Dev" });
    expect(client.apiPost).toHaveBeenCalledWith(
      "/api/workspaces/ws-1/teams",
      expect.objectContaining({ name: "Dev" }),
      "ws-1"
    );
  });
});

describe("updateTeam", (): void => {
  it("patches team endpoint", async (): Promise<void> => {
    vi.mocked(client.apiPatch).mockResolvedValueOnce({ id: "t1", name: "Platform" } as never);
    await updateTeam("t1", { name: "Platform" });
    expect(client.apiPatch).toHaveBeenCalledWith(
      "/api/workspaces/ws-1/teams/t1",
      expect.objectContaining({ name: "Platform" }),
      "ws-1"
    );
  });
});

describe("fetchTeamMembers", (): void => {
  it("calls members endpoint for team", async (): Promise<void> => {
    vi.mocked(client.apiGet).mockResolvedValueOnce([] as never);
    await fetchTeamMembers("t-1");
    expect(client.apiGet).toHaveBeenCalledWith("/api/workspaces/ws-1/teams/t-1/members", "ws-1");
  });
});

describe("deleteTeam", (): void => {
  it("deletes team endpoint", async (): Promise<void> => {
    vi.mocked(client.apiDelete).mockResolvedValueOnce(undefined as never);
    await deleteTeam("t1");
    expect(client.apiDelete).toHaveBeenCalledWith("/api/workspaces/ws-1/teams/t1", "ws-1");
  });
});
