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 UserModel = db.User;
const PlanModel = db.Plan;
import { Op } from 'sequelize';
import { UserData } from '../helpers/userToken';

//get the project list and search by project name
export const getProjectList = async (req: Request, res: Response): Promise<void> => {
    try {
        const { page, per_page, search,client_id, type } = req.query;
        const { limit, offset } = PaginationHelper.getPaginationParams(
            page as string | number | undefined, 
            per_page as string | number | undefined
        );

        // Base where clause
        let whereClause: any = {};

        if(type !== 'all') {
            whereClause.is_active = true
        }

        if (client_id) {
            whereClause = {
                ...whereClause,
                client_id: client_id
            };
        }

        // Add search condition if search parameter exists
        if (search && typeof search === 'string') {
            whereClause = {
                ...whereClause,
                project: {
                    [Op.iLike]: `%${search}%` // Case-insensitive search
                }
            };
        }
        
        const result = await ProjectMasterModel.findAll({
            where: whereClause,
        
            order: [['createdAt', 'DESC']],

            attributes: { 
                exclude: ['createdAt', 'updatedAt'] 
            },
            include: [
                { model: ClientMasterModel, as: 'client', attributes: ['id','client_name','is_active'] }
            ],
        });

        // 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 project list:', error);
        res.status(500).json({ success: false, message: 'Internal server error' });
    }
}

//Create and Edit project Master
export const createProject = async (req: Request, res: Response): Promise<void> => {
    try {
        const { id, project, client_id, is_active } = req.body;
        const userId = (req.user as UserData).user_data.id;

        // if (!project || !client_id ) {
        //     res.status(400).json({ success: false, message: 'Project name, client ID and  are required' });
        //     return;
        // }

        const projectData = {
            project,
            client_id,
            is_active,
            created_by: userId,
        };

        let result;
        if (id) {
            // Update existing project
            result = await ProjectMasterModel.update(projectData, { where: { id } });
        }
        else {
            // Create new project
            result = await ProjectMasterModel.create(projectData);
        }

        let msg
        if (!id) {
            msg = 'Project Created';
        } else if (typeof is_active !== 'undefined') {
            msg = is_active === 'false' || is_active === false ? 'Project Deactivated' : 'Project Updated';
        } else {
            msg = 'Project Updated';
        }
        res.status(200).json({
             success: true, 
             message: msg,         
        });
    } catch (error) {
        console.error('Error creating/updating project:', error);
        res.status(500).json({ success: false, message: 'Internal server error' });
    }
}
