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

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

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

        if (params?.app_id) {
            filterConditions.id = {
                [Op.eq]: params.app_id
            };
        }

        const apps = await dbSAPPS.App.findAll({
            attributes: ['id', 'name', 'display_name', 'app_logo', 'app_logo_secondary', 'app_logo_navbar'],
            where: filterConditions,
            order: [['modified', 'DESC']],

        });

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

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

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

        const apps = await dbSAPPS.App.findAll({
            where: filterConditions,
            order: [['modified', 'DESC']],
            include: [{
                model: dbSAPPS.AppTeam,
                as: 'appteams'
            }]
        });

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

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

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

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

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

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

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

    try {
        const apps = await dbSAPPS.App.findAll({
            where: filterConditions,
            order: [['modified', 'DESC']],
            include: [{
                model: dbSAPPS.AppTeam,
                as: 'appteams'
            }]
        });

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

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

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

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

        const apps = await dbSAPPS.App.findAll({
            attributes: ['id', 'name', 'display_name', 'app_logo'],
            where: filterConditions,
            order: [['name', 'ASC']],
        });

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

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

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

async function create(params) {
    const transaction = await dbSAPPS.sequelize.transaction();
    try {
        if (!params.name || !params.display_name || !params.slug_name) return { success: false, message: 'App name, display name, slug name are required!' };

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

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

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

        const app = await dbSAPPS.App.create(params, { transaction });

        if (params.app_team) {
            params.app_team = JSON.parse(params.app_team);
        }

        if (Array.isArray(params.app_team) && params.app_team.length > 0) {
            const appTeamData = params.app_team.map(appTeam => ({
                ...appTeam,
                app_id: app.id
            }));
            await dbSAPPS.AppTeam.bulkCreate(appTeamData, { transaction });
        }

        await transaction.commit();
        return {
            success: true,
            message: 'App has been created!'
        };
    } catch (error) {
        await transaction.rollback();
        const errorMessage = error.message || 'An error occurred during creating app.';
        return {
            success: false,
            message: errorMessage
        };
    }
}

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

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

            }
        }

        if (params.display_name && params.display_name !== app.display_name) {
            const existingDisplayName = await dbSAPPS.App.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!`
                    };
                }
            }
        }

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

        if (params.app_team) {
            params.app_team = JSON.parse(params.app_team);
        }

        if (Array.isArray(params.app_team) && params.app_team.length > 0) {
            await dbSAPPS.AppTeam.destroy({ where: { app_id: id }, transaction });
            const appTeamData = params.app_team.map(appTeam => ({
                ...appTeam,
                app_id: id
            }));
            await dbSAPPS.AppTeam.bulkCreate(appTeamData, { transaction });
        }

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

async function enabled(id, params) {
    try {
        const app = await dbSAPPS.App.findByPk(id);
        if (!app) return {
            success: false,
            message: 'App 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 app.update(updateData);
        return {
            success: true,
            message: 'App has been updated!'
        };
    } catch (error) {
        const errorMessage = error.message || 'Failed to update app.';
        return {
            success: false,
        }
    }
}
