const test = require('ava')
const supertest = require('supertest')
const app = require('../../../app')
const config = require('../../../config')
const users = require('../../seed/users')

const server = app.listen()
const request = supertest.agent(server)

test.before('Login', async t => {
  const login = await request
    .post('/api/session')
    .send({
      uid: 'admin',
      pwd: config.deploy.adminInitPwd
    })

  t.is(login.status, 200)
})

test.serial('create new group', async t => {
  const create = await request
    .post('/api/group')
    .send({
      title: '测试组2',
      list: [ 'admin' ]
    })

  t.is(create.status, 200)
})

test.serial('Update Group 2', async t => {
  const update = await request
    .put('/api/group/2')
    .send({
      title: '测试组更新2',
      list: [ 'admin' ]
    })
  t.is(update.status, 200)

  const find = await request
    .get('/api/group/2')

  t.is(find.status, 200)
  t.is(find.body.group.title, '测试组更新2')
  t.deepEqual(find.body.group.list, [ 'admin' ])

  const user = await request
    .get('/api/user/admin')

  t.true(user.body.user.gid.includes(2))
})

test.serial('Update Group 2 -- update members', async t => {
  const user = users.data['primaryuser']
  const update = await request
    .put('/api/group/2')
    .send({
      title: '测试组更新2',
      list: [ user.uid ]
    })
  t.is(update.status, 200)

  const find = await request
    .get('/api/group/2')

  t.is(find.status, 200)
  t.is(find.body.group.title, '测试组更新2')
  t.deepEqual(find.body.group.list, [ user.uid ])

  let r = await request
    .get('/api/user/admin')

  t.false(r.body.user.gid.includes(2))

  r = await request
    .get(`/api/user/${user.uid}`)

  t.true(r.body.user.gid.includes(2))
})

test.serial('Delete Group 2', async t => {
  const del = await request
    .delete('/api/group/2')
  t.is(del.status, 200)

  const find = await request
    .get('/api/group/2')

  t.is(find.status, 400)

  const user = await request
    .get('/api/user/admin')

  t.false(user.body.user.gid.includes(2))
})

test.after.always('close server', t => {
  server.close()
})

@@ -2029,24 +2029,554 @@
 des(2))%0A%7D)%0A%0A
+test('The length of group title should be greater than 3', async t =%3E %7B%0A  const res = await request%0A    .post('/api/group')%0A    .send(%7B%0A      title: '1',%0A      list: %5B 'admin' %5D%0A    %7D)%0A%0A  t.is(res.status, 400)%0A  t.truthy(res.body.error)%0A%7D)%0A%0Atest('The length of group title should be less than 80', async t =%3E %7B%0A  const res = await request%0A    .post('/api/group')%0A    .send(%7B%0A      title: Array.from(%7B length: 50 %7D, (_, i) =%3E '' + i).join(''),%0A      list: %5B 'admin' %5D%0A    %7D)%0A%0A  t.is(res.status, 400)%0A  t.truthy(res.body.error)%0A%7D)%0A%0A
 test.after.a

test on group title