import asyncHandler from "#middlewares/asyncHandler";
import { UserWallet } from "#models/user_wallet_model";
import { DailyCheckIn } from "#models/daily_checkin_model";
import { Referral } from "#models/referral_model";


const dailyCheckIn = asyncHandler(async (req, res) => {
    // Find user details
    const userDetails = await UserWallet.findById({ _id: req.params.id });
    if (!userDetails) return res.status(404).json({ status: false, message: "User not found" });

    let checkInData = await DailyCheckIn.findOne({ userId: userDetails._id });

    if (!checkInData) {
        checkInData = new DailyCheckIn({ userId: req.params.id, checkInStreak: 0, lastCheckIn: null });
    }

    const now = new Date();
    const oneDay = 24 * 60 * 60 * 1000; // 24 hours in milliseconds
    // const oneDay = 2 * 60 * 1000; // 24 hours in milliseconds
    const timeSinceLastCheckIn = now - new Date(checkInData.lastCheckIn);

    if (checkInData?.lastCheckIn && timeSinceLastCheckIn < oneDay) {
        // throw new Error('You have already checked in today. Please wait until the next check-in window.');
        return res.status(404).json({ status: true, message: "You have already checked in today" });
    }

    let rewardAmount;
    if (checkInData.lastCheckIn) {
        // User checked in yesterday, increment streak by 100%
        checkInData.checkInStreak += 1;
        console.log(checkInData.checkInStreak,"checkInData.checkInStreak");
        
        // Calculate reward based on streak, doubling each time
        rewardAmount = 10 * Math.pow(2, checkInData.checkInStreak - 1);
        console.log(rewardAmount,"rewardAmountrewardAmountrewardAmount");
    } else {
        // User missed a day or it's the first check-in
        checkInData.checkInStreak = 1;
        rewardAmount = 10; // Starting reward
    }

    checkInData.lastCheckIn = now;
    userDetails.userBalance += rewardAmount;
    userDetails.userLevels += 1;
    console.log(userDetails,"userDetails");
    
    await checkInData.save();
    await userDetails.save();

     // Find referral information
     const referral = await Referral.findOne({ referred_user: userDetails?._id });

     // Check if referral exists and has referring_by field
     if (referral && referral.referring_by) {
         const referrerRewardAmount = userDetails.isPremiumUser ? rewardAmount * 0.08 : rewardAmount * 0.04;
         const referral_by = await UserWallet.findById({ _id: referral.referring_by });
         
         if (referral_by) {
             referral_by.userBalance += referrerRewardAmount;
             await referral_by.save();
             console.log("Referral bonus added to referrer.");
         } else {
             console.log("Referrer not found.");
         }
     }

    return res.status(200).json({ status: true, message: `Check-in successful! You've earned ${rewardAmount} tokens.`});
   
});

// const dailyCheckInStatusChange = asyncHandler(async (req, res) => {
//     // Find user details
//     const userDetails = await UserWallet.findById({ _id: req.params.id });
//     if (!userDetails) return res.status(404).json({ status: false, message: "User not found" });

//     let checkInData = await DailyCheckIn.findOne({ userId: userDetails._id });

//     if (!checkInData) {
//         checkInData = new DailyCheckIn({userId: req.params.id});
//     }

//     const now = new Date();
//     const oneDay = 24 * 60 * 60 * 1000; // 24 hours in milliseconds
//     const timeSinceLastCheckIn = now - new Date(checkInData.lastCheckIn);

//     if (checkInData.lastCheckIn && timeSinceLastCheckIn < oneDay) {
//         // throw new Error('You have already checked in today. Please wait until the next check-in window.');
//         return res.status(404).json({ status: true, message: "You have already checked in today" });
//     }

//     checkInData.lastCheckIn = now;
//     checkInData.checkInStreak += 1;
    
//     const rewardAmount = 10; // 10 tokens
//     userDetails.userBalance += rewardAmount;
//     userDetails.userLevels += 1;
//     console.log(userDetails,"userDetails");
    
//     await checkInData.save();
//     await userDetails.save();

//      // Find referral information
//      const referral = await Referral.findOne({ referred_user: userDetails?._id });

//      // Check if referral exists and has referring_by field
//      if (referral && referral.referring_by) {
//          const referrerRewardAmount = userDetails.isPremiumUser ? rewardAmount * 0.08 : rewardAmount * 0.04;
//          const referral_by = await UserWallet.findById({ _id: referral.referring_by });
         
//          if (referral_by) {
//              referral_by.userBalance += referrerRewardAmount;
//              await referral_by.save();
//              console.log("Referral bonus added to referrer.");
//          } else {
//              console.log("Referrer not found.");
//          }
//      }

//     return res.status(200).json({ status: true, message: `Check-in successful! You've earned ${rewardAmount} tokens.`});
   
// });


const checkUserEligibility = asyncHandler(async (req, res) => {
    try {
      const userCheckIn = await DailyCheckIn.findOne({userId: req.params.id });
  
      // If no record found, user is allowed to check in (i.e., return true)
      if (!userCheckIn) return true;
  
      // Return true or false based on the canCheckIn method
      let checkIn = userCheckIn.canCheckIn();

      if (!userCheckIn) {
        userCheckIn = new DailyCheckIn({ userId: req.params.id, checkInStreak: 0, lastCheckIn: null });
      }
      
      let rewardAmount;

      if (userCheckIn.lastCheckIn) {
          // User checked in yesterday, increment streak by 100%
          userCheckIn.checkInStreak += 1;
          console.log(userCheckIn.checkInStreak,"userCheckIn.checkInStreak");
          
          // Calculate reward based on streak, doubling each time
          rewardAmount = 10 * Math.pow(2, userCheckIn.checkInStreak - 1);
          console.log(rewardAmount,"rewardAmountrewardAmountrewardAmount");
      } else {
          // User missed a day or it's the first check-in
          userCheckIn.checkInStreak = 1;
          rewardAmount = 10; // Starting reward
      }
  

    // console.log(userCheckIn.canCheckIn(),"userCheckIn.canCheckIn()");
      return res.status(200).json({ status: true, checkIn, rewardAmount});
    } catch (error) {
      console.error('Error checking user eligibility:', error);
      return false; // If there's an error, return false
    }
});


export { dailyCheckIn , checkUserEligibility };
