const admin = require('firebase-admin');
const serviceAccount = require('./FCMKEY.json');
const User = require('../models/User'); // Ensure the path is correct based on your file structure
const SmsMessages = require('../models/SmsMessages'); // Import the Sms model

// Initialize Firebase Admin SDK only once
if (!admin.apps.length) {
  admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
  });
}


exports.storeSms = async (req, res) => {
 console.log("recieving  messages started");


const Adresses=['CBE','Awash Bank','251994','127'];
const creditTypes = ['Credited','transfer','deposit','deposited','you have received']
const debitTypes = ['Debited', 'Withdrwal','you have transferred'];
let transactionType = ''

try {
    const userId = req.body.userId;
    const messages = req.body.messages; // Assuming messages is an array of SMS objects
   
   
   
    const allMessages = await SmsMessages.find({ userId: userId }); // Use find instead of findAll
  
    for (const msg of messages) {

      if (!Adresses.includes(msg.address)) {
      //  console.log('This address is not necessary:', msg.address);
        continue;
      }

    
const containscreditType = creditTypes.some(creditType => msg.body.includes(creditType));

if (containscreditType) { 
  console.log('The body contains one of the credit types.');
  transactionType ='credit'
}
else
  {
  //  console.log('The body does not contain any of the credit types.');
   // continue;
  }
  


  const regex = /(?:credited with ETB|Credited with ETB|Deposit of ETB|deposit of ETB) ([\d,]+\.\d{2}|\d{1,3}(,\d{3})*(\.\d{2})?)/g;

  



let match;
let extractedAmount;
while ((match = regex.exec(msg.body)) !== null) {
   extractedAmount = match[1]; // Access the captured amount
  
}


if (extractedAmount) {
  console.log('Extracted Amount:', extractedAmount);
} else {
  //console.log('No amount found in the message.');
  //continue;
}
  
  const amount =Number(extractedAmount)||0;
  const senderName =msg.address;

    //const existingMessage = await SmsMessages.findOne({ id: msg.id, userId: userId });
  
    const newMessageId = msg.id;
    
    const alreadyExist = allMessages.some(message => message.id === newMessageId);
    
   
    



    if (!alreadyExist) {
 // Create a new Date object
  //   const timestamp = msg.date;
  //   const timestampSeconds = timestamp / 1000;

   const date = new Date(msg.date);

    const formattedDate = date.toISOString().replace('T', ' ').substring(0, 19);
   msg.date=formattedDate
   //console.log('Message that will be saved:', msg);
      await SmsMessages.create({ ...msg, userId,amount,senderName }); // Ensure userId is saved along with the message
     
    
      } else {
    //    console.log('Message already exists, skipping:', msg);
      }
    }
    console.log("message saved successfully");
    res.status(200).json({ message: "Messages processed successfully" });
  } catch (error) {
    console.error("Error saving messages:", error);
    res.status(500).json({ message: "Failed to save messages", error: error.message });
  }
};

exports.requestMessage = async (req, res) => {
  const userId =  req.params.userId
  console.log("user id is " + userId);

  const user = await User.findById(userId); // await User.findById(user._id)
  console.log("user is " + user);
  let fcmToken = user.fcmToken;
  sendRequest(fcmToken);
  console.log("fcmToken is : " + fcmToken);

  res.status(200).json({ message: "FCM token sent successfully" });
};

async function sendRequest(token) {
  try {
    // Send FCM message
    const message = {
      notification: { // change 'data' to 'notification' if you want to send a notification that pops up as notification
        title: 'Requesting Message',
        body: 'This is a message requesting from cyberTech Services',
      },
      // Replace with your actual FCM token
      token: token
    };
    const response = await admin.messaging().send(message);
   // console.log('Successfully sent message:', response);
  } catch (error) {
    console.log('Error sending message:', error);
  }
}
