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

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

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

        if (params?.projectsId) {
            filterConditions.project_id = {
                [Op.in]: params?.projectsId
            };
        }

        const documents = await dbSAPPS.Document.findAll({
            where: filterConditions,
            order: [['modified', 'DESC']],
            include: [{
                model: dbSAPPS.User,
                as: 'user',
                attributes: ['email']
            }]
        });

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

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

    if (params?.projectsId) {
        filterConditions.project_id = {
            [Op.in]: params?.projectsId
        };
    }

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

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

    if (params.project_id) {
        filterConditions.project_id = {
            [Op.eq]: params.project_id,
        };
    }

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

    try {
        const documents = await dbSAPPS.Document.findAll({
            where: filterConditions,
            order: [['modified', 'DESC']],
            include: [{
                model: dbSAPPS.User,
                as: 'user',
                attributes: ['email']
            }]
        });

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

async function option() {
    try {
        const documents = await dbSAPPS.Document.findAll({
            attributes: ['id', 'name', 'display_name', 'filename'],
            where: { enabled: true },
            order: [['name', 'ASC']]
        });

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

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

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

async function create(params) {
    try {
        if (!params.name || !params.display_name) return { success: false, message: 'Document name, display name are required!' };

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

        const existingDisplayName = await dbSAPPS.Document.findOne({ where: { display_name: params.display_name } });
        if (existingDisplayName) return { success: false, message: `Display name "${params.display_name}" is already taken.` };

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

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

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

            }
        }

        if (params.display_name && params.display_name !== document.display_name) {
            const existingDisplayName = await dbSAPPS.Document.findOne({ where: { display_name: params.display_name } });
            if (existingDisplayName) {
                if (existingDisplayName.id != params.id) {
                    return {
                        success: false,
                        message: `Display name "${params.display_name}" is already taken. Try again!`
                    };
                }
            }
        }

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

async function enabled(id, params) {
    try {
        const document = await dbSAPPS.Document.findByPk(id);
        if (!document) return {
            success: false,
            message: 'Document 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;

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

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

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

async function getFilename(id) {
    try {
        const document = await dbSAPPS.Document.findByPk(id);
        if (!document) return {
            success: false,
            message: 'Document not found!'
        };

        return {
            success: true,
            filename: document.filename
        };

    } catch (error) {
        const errorMessage = error.message || 'Failed to get document filename.';
        return {
            success: false,
            message: errorMessage
        };
    }
}
