import asyncHandler from "#middlewares/asyncHandler";
import { Referral } from "#models/referral_model";
import { UserWallet, validateUserWallet, validateClaimReward } from "#models/user_wallet_model";

//@desc  Create User
//@route  /initUser
//@request Post Request
//@acess  public
const createUser = asyncHandler(async (req, res) => {
    const { error } = validateUserWallet(req.body);
    if (error) {
        return res.status(400).json({ status: false, message: error.details[0].message });
    }

    const isVerifiedUser = await UserWallet.findOne({ userTelId: req.body.userTelId });

    if (isVerifiedUser) {
        await UserWallet.findOneAndUpdate(
            { userTelId: req.body.userTelId },
            { lastLogin: Date.now() },
            { upsert: true } // Create the user if they don't exist
        );
        return res.status(200).json({ status: true, IsUser: true, lastLogin: isVerifiedUser?.lastLogin });
    }

    let user = new UserWallet(req.body);
    await user.save(); // Save the user to the database

    return res.status(201).json({ status: true, message: "User Registered Successfully!", user });
});


//@desc  Claim Reward
//@route  /claimReward
//@request Post Request
//@access  public
const claimReward = asyncHandler(async (req, res) => {
    const { userTelId, isPremium } = req.body; // Correctly destructuring from req.body

    // Find the user by their Telegram ID
    const isVerifiedUser = await UserWallet.findOne({ userTelId: userTelId });

    // If the user is not found, return an error
    if (!isVerifiedUser) {
        return res.status(400).json({ status: false, message: "User not found." });
    }

    // Ensure userBalance is a number, if not, initialize it to 0
    if (typeof isVerifiedUser.userBalance !== 'number' || isNaN(isVerifiedUser.userBalance)) {
        isVerifiedUser.userBalance = 0;
    }

    // Update user balance based on whether they are premium
    if (isPremium) {
        isVerifiedUser.userBalance += 20; // Add 20 if the user is premium
    } else {
        isVerifiedUser.userBalance += 10; // Add 10 if the user is not premium
    }
    isVerifiedUser.isVerified = true;
    // Save the updated user to the database
    await isVerifiedUser.save();

    return res.status(200).json({ status: true, message: "Reward claimed successfully!", user: isVerifiedUser });
});


//@desc  Get User
//@route  /getUser
//@request Get Request
//@acess  public
const getUser = asyncHandler(async (req, res) => {
    console.log(req.params.id, "req.params.id");

    const user = await UserWallet.findOne({ userTelId: req.params.id });
    console.log(user, "user");
    
    const totalReferrals = await Referral.countDocuments({ referring_by: user._id });

    if (!user) {
        return res
            .status(404)
            .json({ status: false, IsUser: false, message: "User not found" });
    }

    return res
        .status(200)
        .json({ status: true, message: "User Details Retrieved Successfully!", user , totalReferrals });
});

//@desc  GetAllUser
//@route  /getAllUser
//@request Get Request
//@acess  public
const getAllUser = asyncHandler(async (req, res) => {

    const isVerifiedUser = await UserWallet.find({});
    return res
        .status(200)
        .json({ status: true, message: "User Details Successfully!", isVerifiedUser });
});


const subscribeYoutube = asyncHandler(async (req, res) => {
    const { userBackendId, isSubscribe } = req.body;
    if (!isSubscribe) return res.status(400)
        .json({ status: true, message: "Please subscribe first!" });
    const userDetails = await UserWallet.findOne({ _id: userBackendId });
    // 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 ? 10 * 0.08 : 10 * 0.04; //Youtube reward
        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.");
        }
    }

    // userDetails.userBalance += 20;
    userDetails.isYoutubeSubscribe = true;
    // userDetails.userLevels += 1;
    await userDetails.save()

    return res
        .status(200)
        .json({ status: true, message: "User Successfully Subscribe!" });
});

//@desc  claimTwitterAndYoutubeReward
//@route  /claimTwitterAndYoutubeReward
//@request Post Request
//@access  public
const claimTwitterAndYoutubeReward = asyncHandler(async (req, res) => {
    const { userBackendId, Claimtype } = req.body; // Correctly destructuring from req.body

    // Find the user by their Telegram ID
    const isVerifiedUser = await UserWallet.findOne({ _id: userBackendId });

    // If the user is not found, return an error
    if (!isVerifiedUser) {
        return res.status(400).json({ status: false, message: "User not found." });
    }

    // Ensure userBalance is a number, if not, initialize it to 0
    if (typeof isVerifiedUser.userBalance !== 'number' || isNaN(isVerifiedUser.userBalance)) {
        isVerifiedUser.userBalance = 0;
    }

    if (Claimtype == "Twitter") {
        // Check if both tasks are completed
        if (isVerifiedUser.isTwitterConnected) {
            // Check if the reward has already been claimed
            if (isVerifiedUser.hasClaimedTwitterReward) {
                return res.status(200).json({ status: true, message: "Reward already claimed!" });
            } else {
                if (isVerifiedUser?.isPremiumUser) {
                    isVerifiedUser.userBalance += 20; // Twitter Reward Claimed Amount
                } else {
                    isVerifiedUser.userBalance += 10; // Twitter Reward Claimed Amount user is not premium
                }
                // Update user balance based on whether they are premium
                isVerifiedUser.hasClaimedTwitterReward = true;
                // Save the updated user to the database
                isVerifiedUser.userLevels += 1;
                await isVerifiedUser.save();
            }
            return res.status(200).json({ status: true, message: "Congrates You Claimed Twitter Reward" });
        }
    } else if (isVerifiedUser.isYoutubeSubscribe) {
        if (isVerifiedUser.hasClaimedYoutubeReward) {
            return res.status(200).json({ status: true, message: "Reward already claimed!" });
        } else {
            if (isVerifiedUser?.isPremiumUser) {
                isVerifiedUser.userBalance += 20; // Twitter Reward Claimed Amount
            } else {
                isVerifiedUser.userBalance += 10; // Twitter Reward Claimed Amount user is not premium
            }
            // Update user balance based on whether they are premium
            isVerifiedUser.hasClaimedYoutubeReward = true;
            // Save the updated user to the database
            isVerifiedUser.userLevels += 1;
            await isVerifiedUser.save();
        }
        return res.status(200).json({ status: true, message: "Congrates You Claimed Youtube Reward" });
    }
    return res.status(200).json({ status: true, message: "Please complete Task First" });
});

export { createUser, getUser, claimTwitterAndYoutubeReward, getAllUser, claimReward, subscribeYoutube }