const chai = require('chai')
const sinon = require('sinon')
const { faker } = require('@faker-js/faker')
const expect = chai.expect

const OrgRepository = require('../../../src/repositories/orgRepository.js')
const UserRepository = require('../../../src/repositories/userRepository.js')
const { ORG_CREATE_SINGLE } = require('../../../src/controller/org.controller/org.controller.js')

const stubAdpOrg = {
  short_name: 'adpOrg',
  name: 'test_adp',
  authority: {
    active_roles: [
      'ADP'
    ]
  },
  policies: {
    id_quota: 200
  }
}

const stubAdpCnaOrg = {
  short_name: 'cnaAdpOrg',
  name: 'testCnaAdp',
  authority: {
    active_roles: [
      'ADP',
      'CNA'
    ]
  },
  policies: {
    id_quota: 200
  }
}

describe('Testing creating orgs with the ADP role', () => {
  let status, json, res, next, getOrgRepository, orgRepo, getUserRepository,
    userRepo, updateOrg
  beforeEach(() => {
    status = sinon.stub()
    json = sinon.spy()
    res = { json, status }
    next = sinon.spy()
    status.returns(res)

    orgRepo = new OrgRepository()
    getOrgRepository = sinon.stub()
    getOrgRepository.returns(orgRepo)

    userRepo = new UserRepository()
    getUserRepository = sinon.stub()
    getUserRepository.returns(userRepo)

    sinon.stub(orgRepo, 'findOneByShortName').returns(null)
    // Used to get newOrg object
    updateOrg = sinon.stub(orgRepo, 'updateByOrgUUID').returns(true)
    sinon.stub(orgRepo, 'aggregate').returns(true)
    sinon.stub(orgRepo, 'getOrgUUID').returns(true)
    sinon.stub(userRepo, 'getUserUUID').returns(true)
  })
  it('Should return newly created org with id_quota of 0 and ADP role', async () => {
    const req = {
      ctx: {
        uuid: faker.datatype.uuid(),
        repositories: {
          getOrgRepository,
          getUserRepository
        },
        body: {
          ...stubAdpOrg
        }
      }
    }

    await ORG_CREATE_SINGLE(req, res, next)

    expect(status.args[0][0]).to.equal(200)
    expect(updateOrg.args[0][1].policies.id_quota).to.equal(0)
    expect(updateOrg.args[0][1].authority.active_roles[0]).to.equal('ADP')
  })

  it('Should have nonzero id_quota when created with ADP and CNA role', async () => {
    const req = {
      ctx: {
        uuid: faker.datatype.uuid(),
        repositories: {
          getOrgRepository,
          getUserRepository
        },
        body: {
          ...stubAdpCnaOrg
        }
      }
    }

    await ORG_CREATE_SINGLE(req, res, next)

    expect(status.args[0][0]).to.equal(200)
    expect(updateOrg.args[0][1].policies.id_quota).to.equal(200)
    expect(updateOrg.args[0][1].authority.active_roles[0]).to.equal('ADP')
    expect(updateOrg.args[0][1].authority.active_roles[1]).to.equal('CNA')
  })
})
