const dbSAPPS = require('../../helpers/db');
require('dotenv').config();
const { Op } = require('sequelize');

module.exports = {
    create,
    getAll,
    filter,
    option,
    count,
    update,
    enabled,
    delete: _delete
};

async function getAll(params) {
    try {
        const filterConditions = {};

        if (params.projectManagementsId) {
            filterConditions.id = {
                [Op.in]: params.projectManagementsId
            };
        }

        const projectManagements = await dbSAPPS.ProjectManagement.findAll({
            where: filterConditions,
            order: [['modified', 'DESC']],
        });

        return {
            projectManagements,
            success: true,
            message: 'Projects(s) has been loaded!'
        };
    } catch (error) {
        const errorMessage = error.message || 'Failed to load projects(s)!';
        return {
            success: false,
            message: errorMessage
        };
    }
}

async function filter(params) {
    const filterConditions = {};

    if (params.projectManagementsId) {
        filterConditions.id = {
            [Op.in]: params.projectManagementsId
        };
    }

    if (params.project_name) {
        filterConditions.project_name = {
            [Op.like]: `%${params.project_name}%`,
        };
    }

    if (params.enabled) {
        filterConditions.enabled = {
            [Op.eq]: params.enabled === "1" ? true : false,
        };
    }

    try {
        const projectManagements = await dbSAPPS.ProjectManagement.findAll({
            where: filterConditions,
            order: [['modified', 'DESC']],
        });

        return {
            projectManagements,
            success: true,
            message: 'Project(s) has been loaded!'
        };
    } catch (error) {
        console.error('Error retrieving project Managements: ', error);
        const errorMessage = error.message || 'Failed to retrieve project Managements. Please try again later.';
        return {
            success: false,
            message: errorMessage
        };
    }
}

async function option(params) {
    try {
        const filterConditions = {};

        if (params.projectManagementsId) {
            filterConditions.id = {
                [Op.in]: params.projectManagementsId
            };
        }

        filterConditions.enabled = {
            [Op.eq]: true
        };

        const projectManagements = await dbSAPPS.Company.findAll({
            attributes: ['id', 'project_name'],
            where: filterConditions,
            order: [['name', 'ASC']],
            // include: [
            //     {
            //         model: dbSAPPS.ClientType,
            //         as: 'clienttypes',
            //         attributes: ['id', 'display_name', 'code'],
            //         as: 'clienttypes',
            //         include: [
            //             {
            //                 model: dbSAPPS.Specialist,
            //                 as: 'specialists',
            //                 attributes: ['id', 'display_name', 'code'],
            //                 include: [
            //                     {
            //                     model:dbSAPPS.SubSpecialist,
            //                     as: 'subspecialists',
            //                     attributes: ['id', 'display_name', 'code']
            //                     }
            //                 ]
            //             },
            //             {
            //                 model: dbSAPPS.ClientSubtype,
            //                 as: 'clientsubtypes',
            //                 attributes: ['id', 'display_name', 'code'],
            //             }
            //         ]
            //     }
            // ]
        });

        return {
            projectManagements,
            success: true,
            message: 'Project(s) has been loaded!'
        };
    } catch (error) {
        console.error('Error retrieving Project(s): ', error);
        const errorMessage = error.message || 'Failed to retrieve Project(s). Please try again later.';
        return {
            success: false,
            message: errorMessage
        };
    }
}

async function count() {
    try {
        const count = await dbSAPPS.ProjectManagement.count({
            where: { enabled: true }
        });

        return {
            count,
            success: true,
            message: 'Project(s) has been loaded!'
        };
    } catch (error) {
        console.error('Error retrieving Project(s): ', error);
        const errorMessage = error.message || 'Failed to retrieve Project(s). Please try again later.';
        return {
            success: false,
            message: errorMessage
        };
    }
}

async function create(params) {
    try {
        if (!params.project_name) return { success: false, message: 'Project name are required!' };
        if (!params.company_id) return { success: false, message: 'Company are required!' };

        const existingName = await dbSAPPS.ProjectManagement.findOne({ where: { project_name: params.project_name } });
        if (existingName) return { success: false, message: `Project name "${params.project_name}" is already taken.` };


        await dbSAPPS.ProjectManagement.create(params);
        return {
            success: true,
            message: 'Project has been created!'
        };
    } catch (error) {
        const errorMessage = error.message || 'An error occurred during creating Project.';
        return {
            success: false,
            message: errorMessage
        };
    }
}

async function update(id, params) {
    try {
        const projectManagement = await dbSAPPS.ProjectManagement.findByPk(id);
        if (!projectManagement) return {
            success: false,
            message: 'Project Management not found!'
        };

        if (params.project_name && params.project_name !== projectManagement.project_name) {
            const existingName = await dbSAPPS.ProjectManagement.findOne({ where: { project_name: params.project_name } });
            if (existingName) {
                if (existingName.id != params.id) {
                    return {
                        success: false,
                        message: `Project name "${params.project_name}" is already taken. Try again!`
                    };
                }

            }
        }

        await projectManagement.update(params);
        return {
            success: true,
            message: 'Project has been updated!'
        };
    } catch (error) {
        const errorMessage = error.message || 'Failed to update project.';
        return {
            success: false,
            message: errorMessage
        };
    }
}

async function enabled(id, params) {
    try {
        const company = await dbSAPPS.Company.findByPk(id);
        if (!company) return {
            success: false,
            message: 'Company not found!'
        };

        const updateData = {};
        updateData.enabled = params.enabled;
        if (params.modified_by) updateData.modified_by = params.modified_by;
        if (params.modified) updateData.modified = params.modified;

        // debug
        // console.log('id', id);
        // console.log('params', params);
        // console.log('updateData', updateData)

        await company.update(updateData);
        return {
            success: true,
            message: 'Company has been updated!'
        };
    } catch (error) {
        const errorMessage = error.message || 'Failed to update company.';
        return {
            success: false,
            message: errorMessage
        };
    }
}

async function _delete(id) {
    try {
        const company = await dbSAPPS.ProjectManagement.findByPk(id);
        if (!company) return { success: false, message: 'Company not found!' };

        await company.destroy();
        return {
            success: true,
            message: 'Project has been deleted!'
        };
    } catch (error) {
        const errorMessage = error.message || 'Failed to delete company.';
        return {
            success: false,
            message: errorMessage
        };
    }
}
