import { describe, it, expect, vi, beforeEach } from 'vitest'
import { ordersService, CreateOrderRequest } from './ordersService'
import { apiClient } from './apiClient'

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

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

    describe('listOrders', () => {
        it('should fetch orders list', async () => {
            const mockOrders = {
                orders: [
                    { id: 'order-1', buyer_id: 'buyer-1', seller_id: 'seller-1', status: 'Pendente', total_cents: 10000 },
                    { id: 'order-2', buyer_id: 'buyer-1', seller_id: 'seller-2', status: 'Pago', total_cents: 25000 }
                ],
                total: 2,
                page: 1,
                page_size: 20
            }

            vi.mocked(apiClient.get).mockResolvedValue(mockOrders)

            const result = await ordersService.listOrders()

            expect(apiClient.get).toHaveBeenCalledWith('/v1/orders')
            expect(result).toEqual(mockOrders)
        })

        it('should handle empty orders list', async () => {
            const mockOrders = {
                orders: [],
                total: 0,
                page: 1,
                page_size: 20
            }

            vi.mocked(apiClient.get).mockResolvedValue(mockOrders)

            const result = await ordersService.listOrders()

            expect(result).toEqual(mockOrders)
        })

        it('should handle API error', async () => {
            vi.mocked(apiClient.get).mockRejectedValue(new Error('Internal Server Error'))

            await expect(ordersService.listOrders())
                .rejects.toThrow('Internal Server Error')
        })
    })

    describe('createOrder', () => {
        it('should create an order successfully', async () => {
            const orderData: CreateOrderRequest = {
                buyer_id: 'buyer-1',
                seller_id: 'seller-1',
                items: [
                    { product_id: 'prod-1', quantity: 2, unit_cents: 1500, batch: 'L001', expires_at: '2025-12-31' }
                ],
                shipping: {
                    recipient_name: 'Test User',
                    street: 'Rua Test',
                    number: '123',
                    district: 'Centro',
                    city: 'City',
                    state: 'ST',
                    zip_code: '12345-678',
                    country: 'Brasil'
                },
                payment_method: 'pix'
            }

            const mockOrder = {
                id: 'new-order-1',
                ...orderData,
                status: 'Pendente',
                total_cents: 3000,
                created_at: new Date().toISOString()
            }

            vi.mocked(apiClient.post).mockResolvedValue(mockOrder)

            const result = await ordersService.createOrder(orderData)

            expect(apiClient.post).toHaveBeenCalledWith('/v1/orders', orderData)
            expect(result).toEqual(mockOrder)
        })

        it('should handle order creation failure', async () => {
            vi.mocked(apiClient.post).mockRejectedValue(new Error('Insufficient stock'))

            const orderData: CreateOrderRequest = {
                buyer_id: 'buyer-1',
                seller_id: 'seller-1',
                items: [],
                shipping: {
                    recipient_name: '',
                    street: '',
                    number: '',
                    district: '',
                    city: '',
                    state: '',
                    zip_code: '',
                    country: ''
                },
                payment_method: 'pix'
            }

            await expect(ordersService.createOrder(orderData))
                .rejects.toThrow('Insufficient stock')
        })
    })
})
