import React from "react";
import { render } from "@testing-library/react";
import SearchPage from "@/app/(public)/search/page";
import { SearchResults } from "@/app/(public)/search/SearchResults";
import { searchProducts } from "@/lib/product-actions";
import { vi, describe, it, expect, beforeEach } from "vitest";

// Mock the server action in its correct location
vi.mock("@/lib/product-actions", () => ({
  searchProducts: vi.fn(),
}));

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

// Mock the ProductRecommendationCarouselCard component
vi.mock("@/components/showcase/ProductRecommendationCarouselCard", () => ({
  ProductRecommendationCarouselCard: ({ ProductName }: any) => (
    <div data-testid="product-card">{ProductName}</div>
  ),
}));

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

  it("should fetch search results on the server via SearchResults", async () => {
    const mockProducts = {
      success: true,
      data: {
        total: 2,
        documents: [
          { id: "1", title: "Apple iPhone", price: "999.00", image: "" },
          { id: "2", title: "Apple MacBook", price: "1999.00", image: "" }
        ]
      }
    };
    vi.mocked(searchProducts).mockResolvedValue(mockProducts as any);

    // Test SearchResults directly as it is the async part
    const ResultsComponent = await SearchResults({ query: "apple" });
    const { getAllByTestId, getByText } = render(ResultsComponent);

    // Verify server-side fetch was called with correct parameters
    expect(searchProducts).toHaveBeenCalledWith({
        page: 1,
        pageSize: 50,
        query: "apple",
        requestType: "display",
        sortOrder: "ASC"
    });

    // Verify the data was rendered
    expect(getByText('Suchergebnisse für "apple"')).toBeDefined();
    expect(getAllByTestId("product-card")).toHaveLength(2);
    expect(getByText("Apple iPhone")).toBeDefined();
    expect(getByText("Apple MacBook")).toBeDefined();
  });

  it("should handle empty search query correctly", async () => {
    vi.mocked(searchProducts).mockResolvedValue({ success: true, data: { total: 0, documents: [] } } as any);

    await SearchResults({ query: "" });

    expect(searchProducts).toHaveBeenCalledWith({
        page: 1,
        pageSize: 50,
        query: "",
        requestType: "display",
        sortOrder: "ASC"
    });
  });

  it("should show 'no products found' message when search returns no results", async () => {
    vi.mocked(searchProducts).mockResolvedValue({ success: true, data: { total: 0, documents: [] } } as any);

    const ResultsComponent = await SearchResults({ query: "nonexistent" });
    const { getByText } = render(ResultsComponent);

    expect(getByText("Keine Produkte gefunden.")).toBeDefined();
  });
});
