import { UserWallet } from "#models/user_wallet_model";
import { DailyCheckIn } from "#models/daily_checkin_model";
import { bot } from "../server.js";


export const sendTelegramNotification = async (chatId, message) => {
  const botToken = '7232837063:AAERB7SbhDpW64SdqWVVBhxX2e3hr9oCUUM';
  const url = `https://api.telegram.org/bot${botToken}/sendMessage`;

  const response = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      chat_id: chatId, //chatId,
      text: message
    })
  });

  const data = await response.json();
  console.log(data);
};

const imageUrl = 'https://testserver.javatimescaffe.com/uploads/Welcome5.jpg';

export const sendNotificationToAllUsers = async (message) => {
  const users = await UserWallet.find({}); // Fetch all users from the database
  for (let i = 0; i < users.length; i++) {
    try {

      // Send the image after the message
      await bot.telegram.sendPhoto(users[i].userTelId, imageUrl, {
        caption: "Don't forget to check it out! 🎉" // Optional caption for the image
      });


      // Send the message notification first
      await bot.telegram.sendMessage(users[i].userTelId, message);



      // Add a delay between sending messages to avoid rate limiting
      await new Promise((resolve) => setTimeout(resolve, 2000)); // 2 second delay
    } catch (error) {
      console.error(`Failed to send message or image to user ${users[i].userTelId}:`, error);
    }
  }
};

// export const sendNotificationToAllUsers = async (message) => {
//     const users = await UserWallet.find({});
//     for (let i = 0; i < users.length; i++) {
//       try {
//         await bot.telegram.sendMessage(users[i].userTelId, message);
//         await new Promise((resolve) => setTimeout(resolve, 2000)); // 1 second delay
//       } catch (error) {
//         console.error(`Failed to send message to user ${users[i].telegramId}:`, error);
//       }
//     }
// };

export const sendReminderToInactiveUsers = async () => {
  const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000); // 48 hours ago

  const inactiveUsers = await UserWallet.find({
    lastLogin: { $lt: twoDaysAgo },
  });

  inactiveUsers.forEach(async (user) => {
    try {
      await bot.telegram.sendMessage(user.userTelId, 'You haven’t logged in for two days! Please log in and claim your reward.');
    } catch (error) {
      console.error(`Failed to send message to user ${user.userTelId}:`, error);
    }
  });
};

export const sendClaimNotification = async () => {
  try {
    const now = new Date();
    const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);

    // Find users who checked in exactly 24 hours ago
    const usersToNotify = await DailyCheckIn.find({lastCheckIn: { $lte: oneDayAgo }});

    usersToNotify.forEach(async (user) => {
      const userDetails = await UserWallet.findById({ _id: user.userId });
      if (userDetails) {
        bot.telegram.sendMessage(userDetails.userTelId, 'Your check-in reward is now available to claim!');
      }
    });
  } catch (error) {
    console.error('Error sending claim notifications:', error);
  }
};