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

const { USER_CREATE_SINGLE } = require('../../../src/controller/org.controller/org.controller')

const UserRepository = require('../../../src/repositories/userRepository')
const OrgRepository = require('../../../src/repositories/orgRepository')

const stubOrgUUID = faker.datatype.uuid()

const stubOrg = {
  short_name: 'stubOrg',
  name: 'test_user',
  UUID: stubOrgUUID,
  authority: {
    active_roles: ['ADMIN', 'CNA']
  }
}

const stubUser = {
  username: 'stubUser',
  org_UUID: stubOrgUUID,
  UUID: faker.datatype.uuid()
}

describe('Testing the POST /org/:shortname/user endpoint in Org Controller', () => {
  let status, json, res, next, orgRepo, getOrgRepository, getUserRepository, userRepo, req, getOrg

  beforeEach(() => {
    status = sinon.stub()
    json = sinon.spy()
    res = { json, status }
    next = sinon.spy()
    status.returns(res)

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

    orgRepo = new OrgRepository()
    getOrgRepository = sinon.stub()
    getOrgRepository.returns(orgRepo)
    // May have to replace this based on tests
    getOrg = sinon.stub(orgRepo, 'getOrgUUID').returns(stubOrgUUID)
    sinon.stub(userRepo, 'findUsersByOrgUUID').returns(1)
    sinon.stub(orgRepo, 'isSecretariatUUID').returns(false)
    sinon.stub(userRepo, 'isAdminUUID').returns(true)
    sinon.stub(userRepo, 'findOneByUserNameAndOrgUUID').returns(null)
    sinon.stub(userRepo, 'updateByUserNameAndOrgUUID').returns(true)
    sinon.stub(userRepo, 'aggregate').returns([stubUser])
    sinon.stub(userRepo, 'getUserUUID').returns(stubUser.UUID)

    req = {
      ctx: {
        org: stubOrg.short_name,
        uuid: stubOrg.UUID,
        params: {

        },
        repositories: {
          getOrgRepository,
          getUserRepository
        },
        body: {
          stubUser
        }
      }
    }
  })
  context('Positive Tests', () => {
    it('User is created', async () => {
      await USER_CREATE_SINGLE(req, res, next)
      expect(status.args[0][0]).to.equal(200)
      expect(res.json.args[0][0].message).contains('was successfully created')
    })
  })
  context('Negitive tests', () => {
    it('User Fails to be created because not in the same org', async () => {
      req.ctx.org = 'FakeShortName'
      getOrg.withArgs('FakeShortName').returns('FAKEUUID')
      await USER_CREATE_SINGLE(req, res, next)
      expect(status.args[0][0]).to.equal(403)
      expect(res.json.args[0][0].error).contains('NOT_ORG_ADMIN_OR_SECRETARIAT')
    })
  })
})
