import Fetcher from '../../../common/util/Fetcher'
import makeFakeFetch from '../../../../tests/util/fakeFetch'
import { jsoniblePromise } from '../../../common/util/jsonify'

import { handleItemAnalysesResponse } from '../../../common/api/callHandlers'
import { associateItemAnalyses } from '../../../common/actions/quizzes'

import { getItemAnalyses } from '../itemAnalyses'

describe('reporting api actions', () => {
  const quizId = '123'
  const itemId = '456'

  const itemAnalysisData = [{item_id: itemId, item_analysis: {}}]

  const fetchStub = sinon.stub()
  const dispatchStub = sinon.stub()
  const dispatchStubIgnore = sinon.stub()
  const getStateStub = sinon.stub()

  useFakeFetching({dispatchStub, getStateStub, fetchStub})

  describe('getItemAnalyses', () => {
    const stubbedGetItemAnalysisCall = () => {
      const response = jsoniblePromise([itemAnalysisData])
      Fetcher.fakeFetch = makeFakeFetch(response)
      return getItemAnalyses(quizId)(dispatchStub, getStateStub)
    }

    it('should hit the right endpoint', () => {
      Fetcher.fakeFetch = fetchStub
      getItemAnalyses(quizId)(dispatchStubIgnore, getStateStub)
      expect(fetchStub).to.have.been.calledWithMatch(`/api/quizzes/${quizId}/stats/item_analyses/`)
    })

    it('should trigger additional actions', async () => {
      await stubbedGetItemAnalysisCall()

      const expectedHandleResponse = handleItemAnalysesResponse([itemAnalysisData])
      const expectedAssociateResponse = associateItemAnalyses(quizId, [itemAnalysisData])
      checkActionDispatched(dispatchStub, expectedHandleResponse[0])
      checkActionDispatched(dispatchStub, expectedAssociateResponse)
    })
  })
})
