const { errors } = require('cozy-konnector-libs')
const { findUserPdl } = require('../src/findUserPdl')
const xml2js = require('xml2js')

var mockParseUserPdl

// Function to mock in order to test findUserPdl()
jest.mock('../src/parsing', () => ({
  parseUserPdl: (mockParseUserPdl = jest.fn()),
}))

// Dependencies
jest.spyOn(xml2js, 'parseStringPromise').mockResolvedValue('response')
jest.mock('easy-soap-request', () =>
  jest.fn().mockResolvedValue({
    response: {
      body: 'test',
    },
  })
)

describe('recherchePoint', () => {
  it('should throw LOGIN_FAILED for too many responses', async () => {
    mockParseUserPdl.mockImplementationOnce(() => {
      throw new Error('fail')
    })

    try {
      await findUserPdl(
        'azertyuiop',
        'apiKey',
        'login@user.com',
        'John',
        '1 street',
        '69069',
        '69069'
      )
      expect(true).toBe(false)
    } catch (error) {
      expect(error).toBe(errors.LOGIN_FAILED)
    }
  })

  it('should return a correct pdl number', async () => {
    mockParseUserPdl.mockResolvedValue('12345')
    expect(
      await findUserPdl(
        'azertyuiop',
        'apiKey',
        'login@user.com',
        'John',
        '1 street',
        '69069',
        '69069'
      )
    ).toBe('12345')
  })
})