import React from "react";
import { render } from "@testing-library/react";
import AttributesPage from "@/app/(private)/dashboard/attributes/overview/page";
import { getAttributes } from "@/actions/catalog";
import { vi, describe, it, expect, beforeEach } from "vitest";

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

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

// Mock the client component to avoid rendering issues in this unit test
vi.mock("@/app/(private)/dashboard/attributes/overview/AttributesOverviewClient", () => ({
  default: ({ initialData }: any) => (
    <div data-testid="attributes-client">
      {initialData.documents.length} attributes loaded
    </div>
  ),
}));

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

  it("should fetch attributes on the server and pass them to the client component", async () => {
    const mockAttributes = {
      success: true,
      data: {
        total: 1,
        documents: [
          { id: 1, name: "Test Attribute" }
        ],
        pagination: { total: 1, page: 2, limit: 20, totalPages: 1 }
      },
      message: "Fetched"
    };
    vi.mocked(getAttributes).mockResolvedValue(mockAttributes as any);

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

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

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

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

  it("should use default parameters when none are provided in URL", async () => {
    vi.mocked(getAttributes).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 AttributesPage({ searchParams });

    // (page 1, size 10) -> limit 10, offset 0
    expect(getAttributes).toHaveBeenCalledWith({ limit: 10, page: 1 });
  });
});
