import Project from '../models/project.model';
import User from '../models/user.model';

function load(req, res, next, id) {
    Project.get(id)
    .then((project) => {
        req.project = project;
        return next();
    })
    .catch(e => next(e));
}

function get(req, res) {
    return res.json(req.project);
}

function create(req, res, next) {
    const project = new Project({
        approvers: req.body.approvers,
        name: req.body.name,
        description: req.body.description,
    });

    project.save()
    .then(savedProject => res.json(savedProject))
    .catch(e => next(e));
}

function update(req, res, next) {
    const project = req.project;
    project.approvers = req.body.approvers;
    project.name = req.body.name;
    project.description = req.body.description;


    project.save()
    .then(savedProject => res.json(savedProject))
    .catch(e => next(e));
}

function list(req, res, next) {
    const { limit = 50, skip = 0 } = req.query;
    Project.list({ limit, skip })
    .then(projects => res.json(projects))
    .catch(e => next(e));
}

function remove(req, res, next) {
    const project = req.project;
    project.remove()
    .then(deletedProject => res.json(deletedProject))
    .catch(e => next(e));
}

function getUsers(req, res, next) {
    const { projectId } = req.params;
    User.find({projectId})
    .then(users => res.json(users))
    .catch(e => next(e));
}

async function getApprovers(req, res, next) {
    const { projectId } = req.params;
    const { approvers } = await Project.findOne({ _id: projectId });
    const users = Promise.all(approvers.map(async (approver) => {
        let user = await User.findOne({ _id: approver });
        const noPasswodUser = user.toObject();
        delete noPasswodUser.password;

        return noPasswodUser;
    }));

    users
        .then(result => res.json(result))
        .catch(e => next(e));
}

export default { load, get, create, update, list, remove, getUsers, getApprovers };

@@ -80,16 +80,60 @@
 .model';
+%0Aimport APIError from '../helpers/APIError';
 %0A%0Afuncti
@@ -355,24 +355,30 @@
 roject);%0A%7D%0A%0A
+async 
 function cre
@@ -549,24 +549,207 @@
 n,%0A    %7D);%0A%0A
+    let exists = await Project.findOne(%7Bname: req.body.name%7D);%0A%0A    if (exists) %7B%0A        next(new APIError(%60Project with name %22$%7Breq.body.name%7D%22 already exists%60, 400, true));%0A    %7D%0A%0A
     project.
@@ -747,32 +747,36 @@
  project.save()%0A
+    
     .then(savedP
@@ -801,32 +801,36 @@
 (savedProject))%0A
+    
     .catch(e =%3E 

throw an error if a project already exists