import { Request, Response } from 'express';
import { PaginationHelper } from '../helpers/paginate';
import db from '../models'; // Adjust the path to your models folder if necessary
const TaskModel = db.Task;
const TaskHistoryModel = db.TaskHistory;
const ProjectMasterModel = db.ProjectMaster;
const ClientMasterModel = db.ClientMaster;
const TrackexNotificationModel = db.TrackexNotification;
const NotificationHistoryModel = db.NotificationHistory;
const UserModel = db.User;
const PlanModel = db.Plan;
import { Parser } from 'json2csv';
import { Op, where } from 'sequelize';
import { UserData } from '../helpers/userToken';
import { sendAdhocMail } from '../helpers/email/emailHelper';
import { WebSocketService } from '../services/WebSocketService';
const TaskWatchModel = db.TaskWatcher;

export const getAllTasks = async (req: Request, res: Response): Promise<void> => {
    try {
        const { page, per_page, search, client_id } = req.query;
        const { limit, offset } = PaginationHelper.getPaginationParams(
            page as string | number | undefined, 
            per_page as string | number | undefined
        );

        // Build the where clause
        let whereClause: any = {
            is_active: true,
            is_released: true
        };

        // Add search condition if search parameter exists
        if (search && typeof search === 'string') {
            whereClause = {
                ...whereClause,
                [Op.and]: [
                    {
                        title: {
                            [Op.iLike]: `%${search}%`
                        }
                    }
                ]
            };
        }

        // Add client_id condition if it exists
        if (client_id) {
            whereClause = {
                ...whereClause,
                client_id: client_id
            };
        }

        const queryOptions = {
            include: [
                {
                    model: ClientMasterModel,
                    as: 'client',
                    required: false,
                    attributes: { 
                        exclude: ['createdAt', 'updatedAt'] 
                    }
                },
                {
                    model: ProjectMasterModel,
                    as: 'project',
                    required: false,
                    attributes: { 
                        exclude: ['createdAt', 'updatedAt'] 
                    }
                },
                {
                    model: UserModel,
                    as: 'assignee',
                    required: false,
                    attributes: { 
                        exclude: ['createdAt', 'updatedAt'] 
                    }
                }
            ],
            where: whereClause,
            // limit,
            // offset,
            // distinct: true,
            order: [['id', 'ASC']]
        };

        const result = await TaskModel.findAll(queryOptions);

        // if (result.count === 0) {
        //     res.status(200).json({ 
        //         success: true, 
        //         data: [],
        //         pagination: {
        //             total_records: 0,
        //             total_perpage: limit,
        //             total_pages: 0,
        //             current_page: 1,
        //             next_page: null,
        //             previous_page: null
        //         }
        //     });
        //     return;
        // }

        const paginatedResult = PaginationHelper.paginate({
            data: result.rows,
            count: result.count,
            per_page: limit,
            page: page as string
        });

        res.status(200).json({
            success: true,
            data: result,
            // pagination: paginatedResult.pagination
        });

    } catch (error) {
        console.error('Error fetching tasks:', error);
        res.status(500).json({
            success: false,
            message: "We hit a snag! Our team is looking into it.",
            error: error instanceof Error ? error.message : 'Unknown error'
        });
    }
};

//task update
export const updateTaskAndCreateHistory = async (req: Request, res: Response): Promise<void> => {
    try {
        const { task_id,user_id, hours } = req.body;
         // Properly type and access the user data from reques
         console.log('assigned_by')
        // Get the user data from request
        const userData = (req as any).user as UserData;
        const assigned_by = req.user.user_data.id;

        console.log(assigned_by,'assigned_by')

        if (hours !== undefined && typeof hours !== 'number') {
            res.status(400).json({
              success: false,
              message: 'Hours must be a number',
            });
            return;
          }
            // 1. Update task
            const updatedTask = await TaskModel.update(
                {
                    task_type: 'planned',
                    assigned_to: user_id,
                    status: 'assigned',
                    is_released: false,
                    task_released: false,
                    never_assigned: false,
                    hours: hours ?? null
                },
                {
                    where: { id: task_id },
                }
            );

            // 2. Create task history
            await TaskHistoryModel.create(
                {
                    task_id,
                    status: 'assigned',
                    task_date: new Date(),
                    user_id: userData.user_data.id
                },
            );

            // 3. Create plan
            await PlanModel.create(
                {
                    task_id,
                    user_id,
                    plan_status: 'draft',
                    task_status:'assigned',
                    assigned_by: assigned_by,
                    is_highlight: false,
                    is_active: true,
                    is_draft: true

                }
            );
            res.status(200).json({
                success: true,
                message: 'Task Assigned successfully',
            });
    }catch (error) {
        console.error('Error updating task:', error);
        res.status(500).json({
            success: false,
            message: "We hit a snag! Our team is looking into it.",
            error: error instanceof Error ? error.message : 'Unknown error'
        });
      }
}

//unassign task API
export const unassignTask = async (req: Request, res: Response): Promise<void> => {
    try {
        const { task_id } = req.body;
        // Properly type and access the user data from request

        // Get the user data from request
        const userData = (req as any).user as UserData;
        const assigned_by = req.user.user_data.email;

        console.log(assigned_by,'assigned_by')
        
        // Start transaction
            // 1. Update task
            const updatedTask = await TaskModel.update(
                {
                    task_type: 'planned',
                    assigned_to: null,
                    status: 'pending',
                    is_released: true,
                    never_assigned: true
                },
                {
                    where: { id: task_id },
                }
            );

            // 2. Create task history
            await TaskHistoryModel.create(
                {
                    task_id,
                    status: 'pending',
                    task_date: new Date(),
                    user_id: req.user.user_data.id,
                },
            );

            // 3. delete plan
            await PlanModel.destroy({
                where: {
                    task_id: task_id,
                    is_active: true
                }
            });

            res.status(200).json({
                success: true,
                message: 'Task Unassigned successfully',
            });
    
    }catch (error) {
        console.error('Error updating task:', error);
        res.status(500).json({
            success: false,
            message: "We hit a snag! Our team is looking into it.",
            error: error instanceof Error ? error.message : 'Unknown error'
        });
      }
    }

    //Highlight the task based on task_id
export const highlightTask = async (req: Request, res: Response): Promise<void> => {
    try {
        const { plan_id } = req.body;
         // Update the plan
            await PlanModel.update({
                is_highlight: true
            },
                {
                    where: {
                    id: plan_id,
                    is_active: true
                }
             }
            );
            res.status(200).json({
                success: true,
                message: 'Task Highlighted successfully',
                // data: updatedTask[1][0]
            });
    }catch (error) {
        console.error('Error updating task:', error);
        res.status(500).json({
            success: false,
            message: "We hit a snag! Our team is looking into it.",
            error: error instanceof Error ? error.message : 'Unknown error'
        });
      }
 }

    //unhifhlight task
export const unhighlightTask = async (req: Request, res: Response): Promise<void> => {
    try {
        const { plan_id } = req.body;
            // Update the plan
            await PlanModel.update({
                is_highlight: false
            },
                {
                    where: {
                    id: plan_id,
                    is_active: true
                }
             }
            );
            res.status(200).json({
                success: true,
                message: 'Task Removed From the Highlist List',
                // data: updatedTask[1][0]
            });
    }catch (error) {
        console.error('Error updating task:', error);
        res.status(500).json({
            success: false,
            message: "We hit a snag! Our team is looking into it.",
            error: error instanceof Error ? error.message : 'Unknown error'
        });
      }
    }  

//publish the task based on status
export const publishTask = async (req: Request, res: Response): Promise<void> => {
    try {
        const  { is_published,plan_date} = req.body;
        let assigned_by = req.user.user_data.id;
        // Get all draft plans that are active

         // Convert and validate the date
          // Convert and validate the date with time
          let formattedDate: Date;
          try {
              // First try parsing as ISO string
              formattedDate = new Date(plan_date);
              
              // Validate minutes and hours
              const minutes = formattedDate.getMinutes();
              const hours = formattedDate.getHours();
              
              if (isNaN(formattedDate.getTime()) || minutes > 59 || hours > 23) {
                  throw new Error('Invalid date or time');
              }
  
              // Format date to ISO string for PostgreSQL
              const isoDate = formattedDate.toISOString();
  
          } catch (error) {
              res.status(400).json({
                  success: false,
                  message: 'Invalid date or time format. Expected format: YYYY-MM-DD HH:mm:ss',
                  details: 'Hours should be 0-23, minutes should be 0-59'
              });
              return;
          }

        const draftPlans = await PlanModel.findAll({
            where: {
                is_active: true,
                is_draft: true
            }
        });

        // If no draft plans found
        if (draftPlans.length === 0) {
            res.status(404).json({
                success: false,
                message: 'No draft plans found to publish'
            });
            return;
        }

        // Get all task IDs from draft plans
        const taskIds = draftPlans.map((plan: { task_id: number }) => plan.task_id);
        //Get all user_id's from draft plans
        // const userIds = draftPlans.map((plan: { user_id: number }) => plan.user_id);

        // To get unique User IDs
        const userIds: number[] = Array.from(
            new Set(draftPlans.map((plan: { user_id: number }) => plan.user_id))
        );      


        // console.log("");
        // console.log("User IDs >>> ", userIds);

        // Update all matching plans
        await PlanModel.update(
            {
                is_published: true,
                is_draft: false,
                plan_date:formattedDate,
                plan_status: 'published',
            },
            {
                where: {
                    task_id: {
                        [Op.in]: taskIds
                    },
                    is_active: true
                }
            }
        );
        //Check if plan_date and createdAt are same day then update the task_type as ad_hoc
        const currentDate = new Date();
        const currentDateString = currentDate.toISOString().split('T')[0];
        const planDateString = formattedDate.toISOString().split('T')[0];
        console.log('currentDateString',currentDateString)
        console.log('planDateString',planDateString)
        if (currentDateString === planDateString) {
            await TaskModel.update(
                {
                    task_type: 'ad_hoc',
                },
                {
                    where: {
                        id: taskIds
                    }
                }
            );

            const tasks = await TaskModel.findAll({
    where: {
        id: taskIds
    },
    include: [{
        model: PlanModel,
        as: 'plans',
        where: {
            is_active: true
        },
        include: [{
            model: UserModel,
            as: 'user',
            attributes: ['id', 'email', 'first_name', 'last_name']
        }]
    },
    {
        model: ClientMasterModel,
        as: 'client',
        attributes: ['client_name']
    },
    {
        model: ProjectMasterModel,
        as: 'project',
        attributes: ['project']
    }]
});

// console.log("Tasks >>> ", tasks);

// Process emails
let userCount: number = 0;
for (const userId of userIds) {
    console.log("");
    console.log(`User ID: ${userId}`, userCount++);
    try {
        // Filter tasks for this specific user
        const userTasks = tasks.filter((task: any) => 
            task.plans?.some((plan: any) => plan.user_id === userId)
        );

        if (userTasks.length > 0) {
            const user = userTasks[0].plans?.find((plan: any) => plan.user?.id === userId)?.user;

            // console.log("");
            // console.log("User Tasks >>> ", userTasks);

            if (user?.email) {
                const taskUrl = 'https://app.trackex.co/login';

                // Sending Individual mail for each Task
                for (const task of userTasks) {
                    const assignedByUser = await UserModel.findOne({ where: { id: assigned_by } });

                    await sendAdhocMail({
                        taskTitle: task.title,
                        firstName: user.first_name,
                        description: task.description,
                        clientName: task.client?.client_name,
                        projectName: task.project?.project,
                        taskUrl,
                        recipientEmail: user.email,
                        assignedBy: assignedByUser?.first_name
                    });

                console.log(`Email sent successfully to ${user.email}`);

                // console.log("2")
                //create Notification table
                const notification = await TrackexNotificationModel.create({
                    task_id: task.id,
                    type: 'ad-hoc_task',
                    title: 'Ad-hoc Task Assigned',
                    text: task.title,
                    user_id: assigned_by
                } );
                    
                await NotificationHistoryModel.create({
                    notification_id: notification.id,
                    target_to: userId,
                    user_id: assigned_by
                });
                
                }

                WebSocketService.getInstance().sendNotification(userId, {
                        type: 'ad-hoc-task',
                        message: 'Ad-hoc Task Assigned',
                        data: {
                            taskCount: userTasks.length,
                            tasks: userTasks.map((task: any) => ({
                                id: task.id,
                                title: task.title
                            }))
                        }
                    });
            }
        }
    } catch (error) {
        console.error(`Error sending email to user ${userId}:`, error);
        // Continue with other users even if one fails
        continue;
    }
}

        }

        res.status(200).json({
            success: true,
            message: `Daily plan launched! The team is now in the know.`,
        });
    } catch (error) {
        console.error('Error publishing tasks:', error);
        res.status(500).json({
            success: false,
            message: "We hit a snag! Our team is looking into it.",
            error: error instanceof Error ? error.message : 'Unknown error'
        });
    }
};

//Create Task API
export const createTask = async (req: Request, res: Response): Promise<void> => {
    try {
        const { id, is_active, title, description, client_id, project_id, task_type, priority, is_task_assigned, user_id, hours } = req.body;
        //handle the description 
        let descriptionText = description,msg;
        if (!description) {
            descriptionText="";
        }
        // Get the user data from request
        const userData = (req as any).user as UserData;
        // console.log('userData',userData)
        let assigned_by = req.user.user_data.id;
        let createdTask;

        if(id){
            if(is_active === false){

                //delete in task histories table
                await TaskHistoryModel.destroy(
                    {
                        where: { task_id: id },
                    }
                );
                //update is_active false in plan table
                await PlanModel.destroy(
                    {
                        where: { task_id: id },
                    }
                );

                const notification = await TrackexNotificationModel.findOne({
                    where: { task_id: id }
                });
            
                if(notification) {
                    await NotificationHistoryModel.destroy({
                        where: { notification_id: notification.id }
                    });
                
                    await TrackexNotificationModel.destroy({
                        where: { id: notification.id }
                    });
                }

                const findTaskWatch = await TaskWatchModel.findOne({
                    where: {task_id: id}
                })

                if(findTaskWatch) {
                    await TaskWatchModel.destroy({
                        where: {id: findTaskWatch.id}
                    });
                }
 
                await TaskModel.destroy(
                    {
                        where: { id: id },
                    }
                );
           
            } else {
                if(is_task_assigned === true){
                    
                    // Updating and Assigning Task immediately
                    const findTask = await TaskModel.findOne({
                        where: {
                            id: id,
                            is_active: true
                        }
                    })
                    if(!findTask) {
                        throw new Error('Oops! Task not found to update.');
                    }

                    // Update Task table
                    await TaskModel.update(
                        {
                            title,
                            description:descriptionText,
                            client_id,
                            project_id,
                            task_type:'ad_hoc',
                            created_by:assigned_by,
                            is_released: false,
                            status: 'assigned',
                            priority,
                            assigned_to: user_id,
                            is_task_assigned: true,
                            hours,
                        },
                        {
                            where: {
                                id: findTask.id
                            }
                        }
                    );

                    //create in plan table
                    const createPlan = await PlanModel.create(
                        {
                            task_id: findTask.id,
                            user_id,
                            plan_status: 'published',
                            task_status:'assigned',
                            assigned_by: assigned_by,
                            is_highlight: false,
                            is_draft: false,
                            is_published: true,
                            plan_date: new Date(),
                        }
                    );

                    //create in task history table
                    await TaskHistoryModel.create(
                        {
                            task_id:findTask.id,
                            status: 'assigned',
                            task_date: new Date(),
                            user_id: assigned_by
                        },
                    );

                    //create Notification table
                    const notification = await TrackexNotificationModel.create(
                        {
                            task_id: findTask.id,
                            type: 'ad-hoc_task',
                            title: 'Ad-hoc Task Assigned',
                            text: title,
                            user_id: assigned_by
                        }
                    );

                    //create Notification Histories table
                    await NotificationHistoryModel.create(
                        {
                            notification_id: notification.id,
                            target_to: user_id,
                            user_id: assigned_by
                        }
                    );

                    const userTasksCount = await TaskModel.count({
                        where: {
                            assigned_to: user_id,
                            is_active: true
                        }
                    });

                    //Send WebSocket Notification to Assigned User
                    WebSocketService.getInstance().sendNotification(user_id, {
                        type: 'ad-hoc_task',
                        message: title,
                        data: {
                            taskCount: userTasksCount,
                            task: {
                                task_id: findTask.id,
                                type: 'Ad-hoc Task',
                                title: 'Ad-hoc Task Assigned',
                                text: title,
                                user_id: assigned_by
                                
                            }
                        }
                    });

                    //Asynchronous Email Notification
                    (async () => {
                        try {
                            const user = await UserModel.findOne({ where: { id: user_id } });
                            const assignedByUser = await UserModel.findOne({ where: { id: assigned_by } });
                            const client = await ClientMasterModel.findOne({ where: { id: client_id } });
                            const project = await ProjectMasterModel.findOne({ where: { id: project_id } });

                            if(user?.email) {
                                const taskUrl = 'https://app.trackex.co/login';
                                await sendAdhocMail({
                                    taskTitle: title,
                                    firstName: user?.first_name,
                                    description: descriptionText,
                                    clientName: client?.client_name,
                                    projectName: project?.project,
                                    taskUrl,
                                    recipientEmail: user.email,
                                    assignedBy: assignedByUser?.first_name
                                })
                            }
                        } catch (error) {
                            console.error('Email send error:', error);
                        }
                    })();
            
                } else {
                    // Updating the Task in Task table
                    const updatedTask = await TaskModel.update(
                        {
                            title,
                            description:descriptionText,
                            client_id,
                            project_id,
                            priority,
                            hours,
                        },
                        {
                            where: { id: id },
                        }
                    );
                }
            }
       }else{
            //get is_task_assigned true then take user_id in the if condition
            if(is_task_assigned ===true){
                // console.log('id',id)
                createdTask = await TaskModel.create(
                    {
                        title,
                        description:descriptionText,
                        client_id,
                        project_id,
                        task_type:'ad_hoc',
                        created_by:assigned_by,
                        is_released: false,
                        status: 'assigned',
                        priority,
                        assigned_to: user_id,
                        is_task_assigned: true,
                        hours,
                    },
                );
                //create in plan table
                await PlanModel.create(
                    {
                        task_id:createdTask.id,
                        user_id,
                        plan_status: 'published',
                        task_status:'assigned',
                        assigned_by: assigned_by,
                        is_highlight: false,
                        is_draft: false,
                        is_published:true,
                        plan_date: new Date(),
                    }
                );
                //create in task history table
                await TaskHistoryModel.create(
                    {
                        task_id:createdTask.id,
                        status: 'assigned',
                        task_date: new Date(),
                        user_id: assigned_by
                    },
                );

                //create Notification table
                const notification = await TrackexNotificationModel.create(
                    {
                        task_id: createdTask.id,
                        type: 'ad-hoc_task',
                        title: 'Ad-hoc Task Assigned',
                        text: createdTask.title,
                        user_id: assigned_by
                    }
                );

                //create Notification Histories table
                await NotificationHistoryModel.create(
                    {
                        notification_id: notification.id,
                        target_to: user_id,
                        user_id: assigned_by
                    }
                );

                const userTasksCount = await TaskModel.count({
                    where: {
                        assigned_to: user_id,
                        is_active: true
                    }
                });

                // console.log("1",user_id)
                //Send WebSocket Notification to Assigned User
                WebSocketService.getInstance().sendNotification(user_id, {
                    type: 'ad-hoc_task',
                    message: createdTask.title,
                    data: {
                        taskCount: userTasksCount,
                        task: {
                            task_id: createdTask.id,
                            type: 'Ad-hoc Task',
                            title: 'Ad-hoc Task Assigned',
                            text: createdTask.title,
                            user_id: assigned_by
                            
                        }
                    }
                });

                // console.log("2");

                //Asynchronous Email Notification
                (async () => {
                    try {
                        const user = await UserModel.findOne({ where: { id: user_id } });
                        const assignedByUser = await UserModel.findOne({ where: { id: assigned_by } });
                        const client = await ClientMasterModel.findOne({ where: { id: client_id } });
                        const project = await ProjectMasterModel.findOne({ where: { id: project_id } });

                        if(user?.email) {
                            const taskUrl = 'https://app.trackex.co/login';
                            await sendAdhocMail({
                                taskTitle: title,
                                firstName: user?.first_name,
                                description: descriptionText,
                                clientName: client?.client_name,
                                projectName: project?.project,
                                taskUrl,
                                recipientEmail: user.email,
                                assignedBy: assignedByUser?.first_name
                            })
                        }
                    } catch (error) {
                        console.error('Email send error:', error);
                    }
                })();
            
            }else{
            
                createdTask = await TaskModel.create(
                    {
                        title,
                        description:descriptionText,
                        client_id,
                        project_id,
                        task_type:'planned',
                        created_by:req.user.user_data.id,
                        status: 'pending',
                        assigned_to: user_id,
                        priority,
                        hours,
                    },
                );
            }
    }
    //get the message based on id and is_active
    
        if(is_active === false){
            msg = "Task removed! Your planning board just got tidier.";
        }else if(id){
            msg = "Task updated! A little tweak goes a long way.";
        }else{
            msg = "Task added! The productivity gods are pleased.";
        }
            res.status(200).json({
                success: true,
                message: msg,
                data: createdTask
            });
    }catch (error) {
        console.error('Error creating task:', error);
        res.status(500).json({
            success: false,
            message: "We hit a snag! Our team is looking into it.",
            error: error instanceof Error ? error.message : 'Unknown error'
        });
      }
    }
    //get the all users without pagination
export const getAllUsers = async (req: Request, res: Response): Promise<void> => {
    try {
        const { page, per_page, search } = req.query;
        // const { limit, offset } = PaginationHelper.getPaginationParams(
        //     page as string | number | undefined, 
        //     per_page as string | number | undefined
        // );

        // Build the where clause
        let whereClause: any = {
            isActive: true,
        };

        // Add search condition if search parameter exists
        if (search && typeof search === 'string') {
            whereClause = {
                ...whereClause,
                [Op.and]: [
                    {
                        first_name: {
                            [Op.iLike]: `%${search}%`
                        }
                    }
                ]
            };
        }

        const queryOptions = {
            where: whereClause,
            order: [['id', 'ASC']]
        };

        const result = await UserModel.findAll(queryOptions);

        // if (result.count === 0) {
        //     res.status(200).json({ 
        //         success: true, 
        //         data: [],
        //         pagination: {
        //             total_records: 0,
        //             total_perpage: limit,
        //             total_pages: 0,
        //             current_page: 1,
        //             next_page: null,
        //             previous_page: null
        //         }
        //     });
        //     return;
        // }

        // const paginatedResult = PaginationHelper.paginate({
        //     data: result.rows,
        //     count: result.count,
        //     per_page: limit,
        //     page: page as string
        // });

        res.status(200).json({
            success: true,
            data: result,
        });

    } catch (error) {
        console.error('Error fetching tasks:', error);
        res.status(500).json({
            success: false,
            message: "We hit a snag! Our team is looking into it.",
            error: error instanceof Error ? error.message : 'Unknown error'
        });
    }
};

// export const getAllTasks = async (req: Request, res: Response): Promise<void> => {
//     try {
//         const { page, per_page, search, client_id } = req.query;
//         const { limit, offset } = PaginationHelper.getPaginationParams(
//             page as string | number | undefined, 
//             per_page as string | number | undefined
//         );

//         // Build the where clause
//         let whereClause: any = {
//             is_active: true,
//             is_released: true
//         };

//         // Add search condition if search parameter exists
//         if (search && typeof search === 'string') {
//             whereClause = {
//                 ...whereClause,
//                 [Op.and]: [
//                     {
//                         title: {
//                             [Op.iLike]: `%${search}%`
//                         }
//                     }
//                 ]
//             };
//         }

//         // Add client_id condition if it exists
//         if (client_id) {
//             whereClause = {
//                 ...whereClause,
//                 client_id: client_id
//             };
//         }

//         const queryOptions = {
//             include: [
//                 {
//                     model: ClientMasterModel,
//                     as: 'client',
//                     required: false,
//                     attributes: { 
//                         exclude: ['createdAt', 'updatedAt'] 
//                     }
//                 },
//                 {
//                     model: ProjectMasterModel,
//                     as: 'project',
//                     required: false,
//                     attributes: { 
//                         exclude: ['createdAt', 'updatedAt'] 
//                     }
//                 },
//                 {
//                     model: UserModel,
//                     as: 'assignee',
//                     required: false,
//                     attributes: { 
//                         exclude: ['createdAt', 'updatedAt'] 
//                     }
//                 }
//             ],
//             where: whereClause,
//             // limit,
//             // offset,
//             // distinct: true,
//             order: [['id', 'ASC']]
//         };

//         const result = await TaskModel.findAll(queryOptions);

//         // if (result.count === 0) {
//         //     res.status(200).json({ 
//         //         success: true, 
//         //         data: [],
//         //         pagination: {
//         //             total_records: 0,
//         //             total_perpage: limit,
//         //             total_pages: 0,
//         //             current_page: 1,
//         //             next_page: null,
//         //             previous_page: null
//         //         }
//         //     });
//         //     return;
//         // }

//         const paginatedResult = PaginationHelper.paginate({
//             data: result.rows,
//             count: result.count,
//             per_page: limit,
//             page: page as string
//         });

//         res.status(200).json({
//             success: true,
//             data: result,
//             // pagination: paginatedResult.pagination
//         });

//     } catch (error) {
//         console.error('Error fetching tasks:', error);
//         res.status(500).json({
//             success: false,
//             message: "We hit a snag! Our team is looking into it.",
//             error: error instanceof Error ? error.message : 'Unknown error'
//         });
//     }
// };


// Export CSV using json2csv
export const exportTasksToCSV = async (req: Request, res: Response): Promise<void> => {
    try {
        const { start_date, end_date } = req.query;

        // Convert and validate the date
        let formattedStartDate: Date;
        let formattedEndDate: Date;
        try {
            // First try parsing as ISO string
                // Set start date to beginning of day (00:00:00)
                formattedStartDate = new Date(start_date as string);
                formattedStartDate.setHours(0, 0, 0, 0);
    
                // Set end date to end of day (23:59:59)
                formattedEndDate = new Date(end_date as string);
                formattedEndDate.setHours(23, 59, 59, 999);

                 // Add timezone offset
                // const offset = formattedStartDate.getTimezoneOffset() * 60000;
                // formattedStartDate = new Date(formattedStartDate.getTime() - offset);
                // formattedEndDate = new Date(formattedEndDate.getTime() - offset);

    
            // Validate the dates
            if (isNaN(formattedStartDate.getTime()) || isNaN(formattedEndDate.getTime())) {
                throw new Error('Invalid date format');
            }

            // // Format date to ISO string for PostgreSQL
            // const isoStartDate = formattedStartDate.toISOString();
            // const isoEndDate = formattedEndDate.toISOString();

        } catch (error) {
            res.status(400).json({
                success: false,
                message: 'Invalid date format. Expected format: YYYY-MM-DD'
            });
            return;
        }

        const tasks = await TaskModel.findAll({
            where: {
                createdAt: {
                    [Op.between]: [formattedStartDate, formattedEndDate]
                }
            },
            include: [
                {
                    model: ClientMasterModel,
                    as: 'client',
                    required: false,
                    attributes: ['client_name'] // Include only the name field
                },
                {
                    model: ProjectMasterModel,
                    as: 'project',
                    required: false,
                    attributes: ['project'] // Include only the name field
                },
                {
                    model: UserModel,
                    as: 'assignee',
                    required: false,
                    attributes: ['first_name', 'last_name'] // Include only the first_name and last_name fields
                },
                {
                    model: PlanModel,
                    as: 'plans',
                    required: false,
                    where: {
                        is_active: true
                    },
                    include: [
                        {
                            model: UserModel,
                            as: 'user',
                            attributes: ['first_name', 'last_name']
                        }
                    ]
                }
            ],
            order: [['id', 'ASC']]
        });

        console.log(tasks, 'tasks')
        if (!tasks || tasks.length === 0) {
            res.status(404).json({
                success: false,
                message: 'No tasks found for the given date range'
            });
            return;
        }

        const csvData = tasks.map((task: any) => ({
            'Task ID': task.id,
            'Task Title': task.title,
            'Task Description': task.description,
            'Client': task.client ? task.client.client_name : null,
            'Project': task.project ? task.project.project : null,
            'Status': task.status,
            'Released?': task.task_released ? 'Yes' : 'No',
            // createdAt: new Date(task.createdAt).toLocaleString('en-US', {
            //     timeZone: 'Asia/Kolkata', // or your specific timezone
            //     year: 'numeric',
            //     month: '2-digit',
            //     day: '2-digit',
            //     hour: '2-digit',
            //     minute: '2-digit',
            //     second: '2-digit'
            // }),
            'Responsibility': task.plans && task.plans[0] && task.plans[0].user ? 
            `${task.plans[0].user.first_name} ${task.plans[0].user.last_name}` : 
            'Unassigned'
        }));
        const json2csvParser = new Parser();
        const csv = json2csvParser.parse(csvData);
        // Format date for filename
        const dateStr = new Date().toISOString().slice(0, 10);
        const fileName = `tasks_${dateStr}.csv`;
        // const fileName = `tasks_${new Date().toISOString()}.csv`;
        res.setHeader('Content-Type', 'text/csv; charset=utf-8');
        res.setHeader('Content-Disposition', 'attachment; filename="' + fileName + '"');
        res.setHeader('Cache-Control', 'no-cache');
        res.setHeader('Pragma', 'no-cache');

        res.status(200).send(csv);
    } catch (error) {
        console.error('Error exporting tasks to CSV:', error);
        res.status(500).json({
            success: false,
            message: "We hit a snag! Our team is looking into it.",
            error: error instanceof Error ? error.message : 'Unknown error'
        });
    }
};


// export const notificationSeen = async (req: Request, res: Response): Promise<void> => {
//     try {
//          const userId = req.user.user_data.id;

//         await NotificationHistoryModel.update(
//             { is_seen: true },
//             {
//                 where: {
//                     target_to: userId,
//                     is_seen: false
//                 }
//             }
//         );

//         res.status(200).json({
//             success: true,
//             message: `Notifications marked as seen.`,
//         });

//     } catch (error) {
//         console.error('Error marking notifications as seen:', error);
//         res.status(500).json({
//             success: false,
//             message: "We hit a snag! Our team is looking into it.",
//             error: error instanceof Error ? error.message : 'Unknown error'
//         });
//     }
// };

// export const getUserNotifications = async (req: Request, res: Response): Promise<void> => {
//     try {
//         const userId = req.user.user_data.id;

//         // Check if any unseen notifications exist
//         const unseenCount = await NotificationHistoryModel.count({
//             where: {
//                 target_to: userId,
//                 is_seen: false
//             }
//         });
        
//         const queryOptions: any = {
//             where: { target_to: userId },
//             include: [
//                 {
//                     model: TrackexNotificationModel,
//                     as: 'notification'
//                 }
//             ],  
//             order: [['createdAt', 'DESC']]
//         };

//         // If all are seen, limit to latest 5
//         if (unseenCount === 0) {
//             queryOptions.limit = 5;
//         }

//         const notifications = await NotificationHistoryModel.findAll(queryOptions);
      
//         res.status(200).json({
//             success: true,
//             unseen_count: unseenCount,
//             data: notifications
//         });
//     } catch (error) {
//         console.error('Error fetching notifications:', error);
//         res.status(500).json({
//             success: false,
//             message: 'Could not fetch notifications',
//             error: error instanceof Error ? error.message : 'Unknown error',
//         });
//     }
// };
