const express = require('express');
const router = express.Router();
const smsController = require('../controllers/smsController');
const SmsMessages = require('../models/SmsMessages');
const mongoose = require('mongoose');
const { ObjectId } = mongoose.Types;
// ✅ Routes

router.post('/save', smsController.storeSms);
router.get('/sendRequest/:userId', smsController.requestMessage );

router.get('/senders/:userId', async (req, res) => {
  try {
   
    console.log('user ID is:=== ' + req.params.userId);
    const userId =  req.params.userId

    const objectUserId = new mongoose.Types.ObjectId(userId);
  

    const senders = await SmsMessages.aggregate([
    {
      $match: { userId:objectUserId  } 
       },
      {
       
        $group: {
          _id: "$senderName",
          address: {$first: "$address"},
          totalMessages: {$sum: 1},
          unreadCount: {
            $sum: {$cond: [{$eq: ["$view", false]}, 1, 0]}
          },
          latestMessage: {$max: "$date"}
        }
      },
      {$sort: {latestMessage: -1}}
    ]);
    res.json(senders);
  } catch (error) {
    res.status(500).json({message: error.message});
  }
});

// Get messages by sender
router.get('/sender/:senderName/:userId', async (req, res) => {
  try {
    console.log('in get sender userId');
    console.log(req.params.senderName);
    console.log(req.params.userId);
    const messages = await SmsMessages.find({
      senderName: req.params.senderName,userId: req.params.userId
    }).sort({date: -1});
    res.json(messages);
  } catch (error) {
    res.status(500).json({message: error.message});
  }
});

// Mark message as viewed
router.put('/message/:id/view', async (req, res) => {
  try {
    const message = await SmsMessages.findByIdAndUpdate(
      req.params.id,
      {$set: {view: true}},
      {new: true}
    );
    res.json(message);
  } catch (error) {
    res.status(500).json({message: error.message});
  }
});

module.exports = router;
















module.exports = router;
