const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

exports.main = async (event) => {
  const {
    id,
  } = event.data

  try {
    const db = cloud.database({
      throwOnNotFound: false
    });
    const _ = db.command
    const doc = db.collection('user').doc(id)
    const {
      data
    } = await doc.get()
    const {
      data: clist
    } = await db.collection('contract').where({
      username: _.eq(data.username)
    }).get()
    const deleteFileList = []
    clist.forEach(item => {
      item.fileIds.forEach(id => {
        deleteFileList.push(id)
      })
    })
    await doc.remove()
    await db.collection('contract').where({
      username: _.eq(data.username)
    }).remove()
    if (deleteFileList.length) {
      await cloud.deleteFile({
        fileList: deleteFileList
      })
    }
    return {
      success: true
    }
  } catch (err) {
    return {
      success: false,
      msg: err.message
    }
  }
}