import React from "react";
import { render } from "@testing-library/react";
import ResponsiblePersonsPage from "@/app/(private)/dashboard/eu-responsible-persons/overview/page";
import { getResponsiblePersons } from "@/actions/catalog";
import { vi, describe, it, expect, beforeEach } from "vitest";

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

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

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

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

  it("should fetch persons on the server and pass them to the client component", async () => {
    const mockData = {
      success: true,
      data: {
        total: 1,
        documents: [
          { id: 1, companyName: "Test RP", email: "rp@test.com", phoneNumber: "123", address: "Addr" }
        ],
        pagination: { total: 1, page: 2, limit: 20, totalPages: 1 }
      }
    };
    vi.mocked(getResponsiblePersons).mockResolvedValue(mockData as any);

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

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

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

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

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

    const searchParams = Promise.resolve({});

    await ResponsiblePersonsPage({ searchParams });

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