const uuid = require('uuid')
const crypto = require('crypto')
const logger = require('@pubsweet/logger')
const mailService = require('pubsweet-component-mail-service')

class User {
  constructor({ UserModel = {} }) {
    this.UserModel = UserModel
  }

  async createUser({ role, body }) {
    const { UserModel } = this
    const { email, firstName, lastName, affiliation, title } = body
    const username = email
    const password = uuid.v4()
    const userBody = {
      username,
      email,
      password,
      passwordResetToken: crypto.randomBytes(32).toString('hex'),
      isConfirmed: false,
      firstName,
      lastName,
      affiliation,
      title,
      editorInChief: role === 'editorInChief',
      admin: role === 'admin',
      handlingEditor: role === 'handlingEditor',
      invitationToken: role === 'reviewer' ? uuid.v4() : '',
    }

    let newUser = new UserModel(userBody)

    newUser = await newUser.save()
    return newUser
  }

  async setupNewUser({ url, role, invitationType, body = {} }) {
    const newUser = await this.createUser({ role, body })

    try {
      if (role !== 'reviewer') {
        mailService.sendSimpleEmail({
          toEmail: newUser.email,
          user: newUser,
          emailType: invitationType,
          dashboardUrl: url,
        })
      }

      return newUser
    } catch (e) {
      logger.error(e.message)
      return { status: 500, error: 'Email could not be sent.' }
    }
  }

  async getEditorInChief() {
    const { UserModel } = this
    const users = await UserModel.all()
    const eic = users.find(user => user.editorInChief || user.admin)
    return eic
  }

  async updateUserTeams({ userId, teamId }) {
    const user = await this.UserModel.find(userId)
    user.teams.push(teamId)
    user.save()
  }
}

module.exports = User