import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import WorkspaceDetailPage from "./page";
import * as workspacesApi from "@/lib/api/workspaces";

vi.mock("next/navigation", () => ({
  useParams: (): { id: string } => ({ id: "ws-test-1" }),
}));

vi.mock("@/lib/auth/auth-context", () => ({
  useAuth: (): { user: { id: string } } => ({ user: { id: "u1" } }),
}));

vi.mock("@/lib/api/workspaces");

vi.mock("@/components/workspace/MemberList", () => ({
  MemberList: ({ members }: { members: unknown[] }): React.ReactElement => (
    <div data-testid="member-list">Members: {members.length}</div>
  ),
}));

const mockWorkspace = {
  id: "ws-test-1",
  name: "Test Workspace",
  ownerId: "u1",
  role: "OWNER",
  createdAt: "2024-01-01",
};

const mockMembers = [
  {
    workspaceId: "ws-test-1",
    userId: "u1",
    role: "OWNER",
    joinedAt: "2024-01-01",
    user: { id: "u1", email: "a@b.com", name: "Alice", image: null },
  },
];

beforeEach(() => {
  vi.clearAllMocks();
});

describe("WorkspaceDetailPage", () => {
  it("loads and renders member list", async (): Promise<void> => {
    vi.mocked(workspacesApi.fetchUserWorkspaces).mockResolvedValue([mockWorkspace] as never);
    vi.mocked(workspacesApi.fetchWorkspaceMembers).mockResolvedValue(mockMembers as never);
    render(<WorkspaceDetailPage />);
    await waitFor(() => {
      expect(screen.getByTestId("member-list")).toBeInTheDocument();
    });
    expect(screen.getByText("Test Workspace")).toBeInTheDocument();
  });

  it("shows error state on fetch failure, not member list", async (): Promise<void> => {
    vi.mocked(workspacesApi.fetchUserWorkspaces).mockRejectedValue(new Error("Network error"));
    vi.mocked(workspacesApi.fetchWorkspaceMembers).mockRejectedValue(new Error("Network error"));
    render(<WorkspaceDetailPage />);
    await waitFor(() => {
      expect(screen.getByRole("alert")).toBeInTheDocument();
    });
    expect(screen.queryByTestId("member-list")).not.toBeInTheDocument();
  });
});
