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

// Mock the server action
vi.mock("@/actions/catalog", () => ({
  getBrands: vi.fn(),
  createBrand: vi.fn(),
  updateBrand: vi.fn(),
  deleteBrand: vi.fn(),
}));

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

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

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

  it("should fetch brands on the server and pass them to the client component", async () => {
    const mockBrands = {
      success: true,
      data: {
        total: 1,
        documents: [
          { id: 1, name: "Test Brand", created_at: new Date(), last_updated_at: new Date() }
        ],
        pagination: { total: 1, page: 2, limit: 20, totalPages: 1 }
      }
    };
    vi.mocked(getBrands).mockResolvedValue(mockBrands as any);

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

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

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

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

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

    const searchParams = Promise.resolve({});

    await BrandsPage({ searchParams });

    // page 1, pageSize 10
    expect(getBrands).toHaveBeenCalledWith({ limit: 10, page: 1 });
  });
});
