import { describe, it, expect, vi, beforeEach } from 'vitest'
import { productService } from './productService'
import { apiClient } from './apiClient'
import { ProductSearchFilters } from '../types/product'

vi.mock('./apiClient', () => ({
    apiClient: {
        get: vi.fn(),
    }
}))

describe('productService', () => {
    beforeEach(() => {
        vi.clearAllMocks()
    })

    it('search calls api with correct params', async () => {
        const mockResponse = { data: { products: [], total: 0, page: 1, page_size: 20 } }
        vi.mocked(apiClient.get).mockResolvedValue(mockResponse)

        const filters: ProductSearchFilters = {
            lat: -16.32,
            lng: -48.95,
            search: 'dipirona',
            page: 1,
            page_size: 20
        }

        const result = await productService.search(filters)

        expect(apiClient.get).toHaveBeenCalledWith(
            expect.stringContaining('/v1/products/search')
        )
        // Check if params are present
        const callArgs = vi.mocked(apiClient.get).mock.calls[0][0]
        expect(callArgs).toContain('lat=-16.32')
        expect(callArgs).toContain('lng=-48.95')
        expect(callArgs).toContain('search=dipirona')

        expect(result).toEqual(mockResponse.data)
    })

    it('search handles optional filters', async () => {
        const mockResponse = { data: { products: [], total: 0 } }
        vi.mocked(apiClient.get).mockResolvedValue(mockResponse)

        const filters: ProductSearchFilters = {
            lat: -16.32,
            lng: -48.95,
            min_price: 1000,
            max_price: 5000,
            max_distance: 10
        }

        await productService.search(filters)

        const callArgs = vi.mocked(apiClient.get).mock.calls[0][0]
        expect(callArgs).toContain('min_price=1000')
        expect(callArgs).toContain('max_price=5000')
        expect(callArgs).toContain('max_distance=10')
    })
})
