import { describe, it, expect, vi, afterEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { ProductCard } from './ProductCard'
import type { ProductWithDistance } from '../types/product'

const baseProduct: ProductWithDistance = {
  id: 'prod-1',
  seller_id: 'seller-1',
  name: 'Amoxicilina 500mg',
  description: 'Caixa com 20 cápsulas',
  batch: 'L123',
  expires_at: new Date(Date.now() + 10 * 24 * 60 * 60 * 1000).toISOString(),
  price_cents: 1299,
  stock: 10,
  created_at: new Date().toISOString(),
  updated_at: new Date().toISOString(),
  distance_km: 4.2,
  tenant_city: 'São Paulo',
  tenant_state: 'SP'
}

describe('ProductCard', () => {
  afterEach(() => {
    vi.useRealTimers()
  })

  it('renders expiring soon badge and formats pricing', () => {
    vi.useFakeTimers()
    vi.setSystemTime(new Date('2024-01-01T00:00:00.000Z'))

    const product = {
      ...baseProduct,
      expires_at: new Date('2024-01-15T00:00:00.000Z').toISOString()
    }

    render(<ProductCard product={product} onAddToCart={vi.fn()} />)

    expect(screen.getByText('Vence em breve')).toBeInTheDocument()
    expect(screen.getByText('R$ 12,99')).toBeInTheDocument()
    expect(screen.getByText(/4.2 km/)).toBeInTheDocument()
  })

  it('invokes add to cart handler when clicking the button', async () => {
    const onAddToCart = vi.fn()
    const user = userEvent.setup()

    render(<ProductCard product={baseProduct} onAddToCart={onAddToCart} />)

    await user.click(screen.getByRole('button', { name: 'Adicionar' }))

    expect(onAddToCart).toHaveBeenCalledWith(baseProduct)
  })

  it('does not show expiring badge for long expiry', () => {
    const product = {
      ...baseProduct,
      expires_at: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000).toISOString()
    }

    render(<ProductCard product={product} onAddToCart={vi.fn()} />)

    expect(screen.queryByText('Vence em breve')).not.toBeInTheDocument()
  })
})
