import EventsApi from '../index'
import EnhancedContentApi, { EcRenderConfig } from '../../enhancedContent'
import { makeSettings, makeContext } from '../../__tests__/helpers'

const log = jest.fn()
const ecApi = new EnhancedContentApi(makeSettings(), makeContext(), { log })
const eventsApi = new EventsApi({ log }, undefined, ecApi)

const lastEcRenderConfigSpy = jest.spyOn(ecApi, 'lastRenderConfig', 'get')

const eventOptions = {
  productIdType: 'test-id-type',
  productId: 'test-id',
}

describe('EventsApi', () => {
  describe('navigation', () => {
    test('it emits the navigation event with the correct options', async () => {
      eventsApi.navigation(eventOptions)
      expect(log).toHaveBeenCalledWith('navigation', eventOptions)
    })
  })

  describe('addToCart', () => {
    const atcEventOptions = { ...eventOptions, quantity: 1 }

    test('it emits the add_to_cart event with the correct options', async () => {
      lastEcRenderConfigSpy.mockReturnValue(undefined)
      eventsApi.addToCart(atcEventOptions)
      expect(log).toHaveBeenCalledWith('add_to_cart', { ...atcEventOptions, lastEcRender: undefined })
    })

    test('it emits the add_to_cart event with the correct options after render', async () => {
      const lastEcRenderConfig: EcRenderConfig = {
        productId: '1234',
        idType: 'SKU',
        content: [
          { source: 'foo.html', weight: 0.95 },
          { source: null, weight: 0.05 },
        ],
        allContentExists: true,
        source: 'foo.html',
        sourceExists: true,
      }
      lastEcRenderConfigSpy.mockReturnValue(lastEcRenderConfig)
      eventsApi.addToCart(atcEventOptions)
      expect(log).toHaveBeenCalledWith('add_to_cart', { ...atcEventOptions, lastEcRenderConfig })
    })
  })
})
