const models = require('../../../database/schemas.js');
const email = require('emailjs');

module.exports = {
  getAllForUser: (req, res) => {
    models.User.findOne({
      where: {
        id: req.params.id,
      },
    })
      .then((user) => {
        user.getMessages({
          include: [
            { model: models.User },
            { model: models.User, as: 'sender' },
            { model: models.Post },
          ],
        })
          .then((messages) => {
            res.json(messages);
          });
      });
  },

  createMessage: (req, res) => {
    // Find the user the message was sent to
    models.User.findOne({ where: { id: req.body.userId } })
    .then((receivingUser) => {
      // Connect to the velocies.raptorads@gmail.com email
      const server = email.server.connect({
        user: 'velociesraptorads',
        password: 'velociesarethebest',
        host: 'smtp.gmail.com',
        ssl: true,
      });

      // Once connected, send the receiving user of the message an email notification
      server.send({
        text: 'Someone sent you a message in response to one of your job listings. You can navigate to your inbox on our website to view this message.',
        from: 'velocies.raptorads@gmail.com',
        to: receivingUser.email,
        subject: 'Response To Your Listing',
      }, (err, message) => { console.log(err || message); });

      models.Message.create(req.body)
        .then((message) => {
          res.json(message);
        });
    });
  },
};

@@ -204,16 +204,42 @@
 ams.id,%0A
+        isDeleted: false,%0A
       %7D,
@@ -297,16 +297,78 @@
 sages(%7B%0A
+          where: %7B%0A            isDeleted: false,%0A          %7D,%0A
         
@@ -752,16 +752,34 @@
 y.userId
+, isDeleted: false
  %7D %7D)%0A  
@@ -803,24 +803,53 @@
 gUser) =%3E %7B%0A
+      if (receivingUser) %7B%0A  
       // Con
@@ -901,16 +901,18 @@
 l%0A      
+  
 const se
@@ -941,16 +941,18 @@
 nnect(%7B%0A
+  
         
@@ -986,16 +986,18 @@
         
+  
 password
@@ -1028,16 +1028,18 @@
         
+  
 host: 's
@@ -1046,32 +1046,34 @@
 mtp.gmail.com',%0A
+  
         ssl: tru
@@ -1081,21 +1081,25 @@
 ,%0A      
+  
 %7D);%0A%0A
+  
       //
@@ -1182,16 +1182,18 @@
 n%0A      
+  
 server.s
@@ -1198,16 +1198,18 @@
 .send(%7B%0A
+  
         
@@ -1361,16 +1361,18 @@
         
+  
 from: 'v
@@ -1409,16 +1409,18 @@
         
+ 
+ 
 to: rece
@@ -1436,16 +1436,18 @@
 .email,%0A
+  
         
@@ -1489,16 +1489,18 @@
 ,%0A      
+  
 %7D, (err,
@@ -1550,24 +1550,26 @@
  %7D);%0A%0A      
+ 
+ 
 models.Messa
@@ -1588,32 +1588,34 @@
 q.body)%0A        
+  
 .then((message) 
@@ -1615,24 +1615,26 @@
 ssage) =%3E %7B%0A
+  
           re
@@ -1654,28 +1654,128 @@
 e);%0A        
+  
 %7D);%0A
+      %7D else %7B%0A        res.send('Could not find a user matching the intended recipient');%0A      %7D%0A
     %7D);%0A  %7D,

Modify messagesController to use 'isDeleted' field