import React from "react";
import { render } from "@testing-library/react";
import UsersPage from "@/app/(private)/dashboard/users/overview/page";
import { getUsers } from "@/actions/user";
import { vi, describe, it, expect, beforeEach } from "vitest";

// Mock the server action module
vi.mock("@/actions/user", () => ({
  getUsers: vi.fn(),
}));

// Mock next/navigation
vi.mock("next/navigation", () => ({
  useRouter: () => ({ push: vi.fn(), refresh: vi.fn() }),
  usePathname: () => "/dashboard/users/overview",
  useSearchParams: () => new URLSearchParams(),
  notFound: vi.fn(),
}));

// Mock the client component
vi.mock("@/app/(private)/dashboard/users/overview/UsersOverviewClient", () => ({
  default: ({ initialData }: any) => (
    <div data-testid="users-client">
      {initialData.documents.length} users loaded
    </div>
  ),
}));

describe("Users Overview Performance: SSR Refactor", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("should fetch users on the server and pass them to the client component", async () => {
    const mockUsers = {
      success: true,
      data: {
        total: 1,
        documents: [
          { id: 1, firstName: "John", lastName: "Doe", email: "j@e.com", role: "user" }
        ],
        pagination: { total: 1, page: 2, limit: 20, totalPages: 1 }
      },
      message: "Fetched"
    };
    vi.mocked(getUsers).mockResolvedValue(mockUsers as any);

    const searchParams = Promise.resolve({
      page: "2",
      pageSize: "20"
    });

    // Call the server component
    const PageComponent = await UsersPage({ searchParams });
    const { getByTestId } = render(PageComponent);

    // Verify server-side fetch was called with correct parameters from URL
    expect(getUsers).toHaveBeenCalledWith({ limit: 20, page: 2, excludeRole: "customer" });

    // Verify the data was passed to the client component
    expect(getByTestId("users-client").textContent).toContain("1 users loaded");
  });

  it("should use default parameters when none are provided in URL", async () => {
    vi.mocked(getUsers).mockResolvedValue({
      success: true,
      data: { total: 0, documents: [], pagination: { total: 0, page: 1, limit: 10, totalPages: 0 } },
      message: "Fetched"
    } as any);

    const searchParams = Promise.resolve({});

    await UsersPage({ searchParams });

    // page 1, size 10
    expect(getUsers).toHaveBeenCalledWith({ limit: 10, page: 1, excludeRole: "customer" });
  });
});
