/**
 * (ListGrid prop contract + empty dataset).
 */
import React from 'react'
import { render, screen } from '@testing-library/react'
import { ProductList } from '../index'
import type { ProductListProps } from '../index'
import { MOCK_API_PRODUCT_LIST_RESPONSE } from '@/_tests_/mocks'

jest.mock('@/components/api-product/card', () => ({
  ProductCard: ({ product }: { product: { name?: string } }) => (
    <div data-testid="mini-card">{`Card: ${product?.name}`}</div>
  ),
}))
const mockListGrid = jest.fn(() => <div data-testid="list-grid-stub">ListGrid</div>)
jest.mock('@/share/components/list-grid', () => ({
  ListGrid: (props: Record<string, unknown>) => mockListGrid(props),
}))

const defaultProps = (): ProductListProps => ({
  products: MOCK_API_PRODUCT_LIST_RESPONSE.data.list,
  limitPerPage: 10,
  defaultPageSize: 10,
  searchQuery: 'loan',
  hasNextPage: true,
  isFetchingNextPage: false,
  fetchNextPage: jest.fn(),
})

describe('[components/api-product/product-list] ProductList', () => {
  beforeEach(() => {
    mockListGrid.mockClear()
  })

  describe('happy path — ListGrid delegation', () => {
    it('maps each product into ProductCard slots and forwards pagination props', () => {
      const props = defaultProps()
      render(<ProductList {...props} />)
      expect(screen.getByTestId('list-grid-stub')).toBeInTheDocument()
      const call = mockListGrid.mock.calls[0]?.[0] as {
        elements: React.ReactElement[]
        limitPerPage: number
        fetchNextPage: unknown
      }
      expect(call.elements).toHaveLength(props.products.length)
      expect(call).toEqual(
        expect.objectContaining({
          limitPerPage: 10,
          defaultPageSize: 10,
          searchQuery: 'loan',
          hasNextPage: true,
          isFetchingNextPage: false,
          fetchNextPage: props.fetchNextPage,
        })
      )
    })

    it('passes zero-length elements array when products empty', () => {
      render(<ProductList {...defaultProps()} products={[]} />)
      expect(
        (mockListGrid.mock.calls[0]?.[0] as { elements: unknown[] }).elements
      ).toHaveLength(0)
      expect(screen.getByTestId('list-grid-stub')).toBeInTheDocument()
    })
  })
})
