import asyncHandler from "#middlewares/asyncHandler";
import { Task, validateTask } from "#models/task_model";
import { TransactionHistory } from "#models/transaction_history_model";
import { Referral } from "#models/referral_model";
import { sendNotification } from "#utils/sendNotification";
import { sendTelegramNotification , sendNotificationToAllUsers} from "#utils/telegramNotification";



const createTask = asyncHandler(async (req, res) => {
    // Validate the request body using the schema validation function
    const { error } = validateTask(req.body);
    if (error) {
        return res.status(400).json({ status: false, message: error.details[0].message });
    }

    // Extract fields from request body
    const {description, reward_amount, type, mcq, openLink, referralTarget } = req.body;

    // Create a new task instance with the provided data
    const task = new Task({description, reward_amount, type });

    // Set specific fields based on task type
    if (type === 'MCQ') {
        task.mcq = mcq;
    } else if (type === 'OpenLink') {
        task.openLink = openLink;
    } else if (type === 'Referral') {
        task.referralTarget = referralTarget;
    }

    // Save the task to the database
    await task.save();
    
    // sendNotification({title:'New Recipe Added', body: `A new recipe has been added to our collection.`},"cyvXoRPhUSKBwQ8lkLPxw1:APA91bHYyG7mA_yeNlkM3rH4kEGJj1vHUoj-JHegWJcXKirvOfQcGSFdZoimxehslW3fDTrxW1ceel2soPtXVVI-JpiLV1nr-c372I3mHx40hJAiO91kRaFL8fZTDd995ZhbWTLpFjer")
    sendNotificationToAllUsers("🚀 Admin has created a new task! Check it out and earn rewards! 🌟");

    // // Fetch all users from UserWallet
    // const users = await UserWallet.find({});

    // // Create a map of referred users to their referrers
    // const referrals = await Referral.find({});
    // const userReferrerMap = new Map(referrals.map(referral => [referral.referred_user.toString(), referral.referring_by]));

    // // Create TransactionHistory entries for each user
    // const transactionHistories = users.map(user => ({
    //     taskId: task._id,
    //     userId: user._id,
    //     referrerId: userReferrerMap.get(user._id.toString()) || null, // Use referrer ID if exists
    //     rewardAmount: task.reward_amount,
    //     taskType: task.type,
    //     status: 'ongoing'
    // }));

    // // Insert TransactionHistory entries into the database
    // await TransactionHistory.insertMany(transactionHistories);

    res.status(201).json({ status: true, message: "Task created successfully and assigned to all users!", task });
});

// //Create Task
// const createTask = asyncHandler(async (req, res) => {
//     // Validate the request body using the schema validation function
//     const { error } = validateTask(req.body);
//     if (error) {
//         return res.status(400).json({ status: false, message: error.details[0].message });
//     }

//     // Extract fields from request body
//     const { name, description, reward_amount, type, mcq, referralTarget } = req.body;

//     // Create a new task instance with the provided data
//     const task = new Task({ name, description, reward_amount, type });

//     // Set specific fields based on task type
//     if (type === 'MCQ') {
//         task.mcq = mcq;
//     }
//     else if (type === 'Referral') {
//         task.referralTarget = referralTarget;
//     }

//     // Save the task to the database
//     await task.save();
//     res.status(201).json({ status: true, message: "Task created successfully!", task });
// });

// const getOneUserPerIncompleteTask = async (req, res) => {
//     try {
//         const userId = req.params.id;

//         // Fetch tasks from TransactionHistory where status is "completed"
//         const rewardClaimPending = await TransactionHistory.find({
//             userId,
//             status: "completed"
//         });

//         // Fetch tasks from TransactionHistory where isUserClaimed is true
//         const rewardClaimed = await TransactionHistory.find({
//             userId,
//             isUserClaimed: true
//         });

//         // Combine task IDs from both queries into a single set for easier exclusion
//         const claimedOrPendingTaskIds = new Set([
//             ...rewardClaimPending.map(tx => tx.taskId.toString()),
//             ...rewardClaimed.map(tx => tx.taskId.toString())
//         ]);

//         // Fetch all tasks
//         const allTasks = await Task.find({}, { 'mcq.correctAnswer': 0 });

//         // Filter out tasks that are either completed or claimed
//         const incompletedTasks = allTasks.filter(task => !claimedOrPendingTaskIds.has(task._id.toString()));

//         res.status(200).json({
//             success: true,
//             readyForClaim: rewardClaimPending,
//             allTask: incompletedTasks // For consistency with your structure
//         });
//     } catch (error) {
//         console.error('Error fetching users for incomplete tasks:', error);
//         res.status(500).json({
//             success: false,
//             message: 'Error fetching users for incomplete tasks',
//         });
//     }
// };

const getOneUserPerIncompleteTask = async (req, res) => {
    try {
        // Fetch all tasks excluding 'correctAnswer' from MCQ schema
        const allTasks = await Task.find({}, { 'mcq.correctAnswer': 0 });
        
        // console.log(req.params.id,"req.params.id");
        // Fetch incomplete transactions for the given user
        const incompleteTransactions = await TransactionHistory.find({
            userId: req.params.id,
            status: "completed"
        }).populate('taskId');

        // Extract task IDs from incomplete transactions
        const AllTaskIds = new Set(incompleteTransactions.map(transaction => transaction.taskId?._id?.toString()));
        
        console.log(AllTaskIds,"AllTaskIdsAllTaskIds");

        // Filter out tasks that do not have a corresponding record in TransactionHistory
        const incompleteTasks = allTasks.filter(task => !AllTaskIds.has(task?._id?.toString()));
        
        const completedTaskIds = incompleteTransactions.filter(transaction => transaction.isUserClaimed === false);

        res.status(200).json({
            success: true,
            incompleteTasks, // Tasks that do not have records in TransactionHistory
            completedTaskIds // All tasks
        });
    } catch (error) {
        console.error('Error fetching tasks for user:', error);
        res.status(500).json({
            success: false,
            message: 'Error fetching tasks for user',
        });
    }
};

// Get All Tasks
const getAllTasks = asyncHandler(async (req, res) => {
    const tasks = await Task.find({}, { 'mcq.correctAnswer': 0 });
    res.status(200).json({ status: true, tasks });
});

// Get Task By ID
const getTaskById = asyncHandler(async (req, res) => {
    const task = await Task.findById(req.params.id);
    if (!task) {
        return res.status(404).json({ status: false, message: "Task not found" });
    }
    res.status(200).json({ status: true, task });
});

// Update Task
const updateTask = asyncHandler(async (req, res) => {
    // Validate the request body using the schema validation function
    // const { error } = validateTask(req.body);
    // if (error) {
    //     return res.status(400).json({ status: false, message: error.details[0].message });
    // }

    // Find and update the task with the provided data
    const task = await Task.findByIdAndUpdate(req.params.id, req.body, { new: true });

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

    res.status(200).json({ status: true, message: "Task updated successfully!", task });
});

// Delete Task
const deleteTask = asyncHandler(async (req, res) => {
    const task = await Task.findByIdAndDelete(req.params.id);
    if (!task) {
        return res.status(404).json({ status: false, message: "Task not found" });
    }
    res.status(200).json({ status: true, message: "Task deleted successfully!" });
});


export { createTask, getAllTasks, getOneUserPerIncompleteTask, getTaskById, updateTask, deleteTask };
