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

module.exports = {
    count,
    getApp,
    getDevelopment,
    getDevelopmentDetail,
    getFeatureCount,
    getCourse,
};

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

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

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

        const countImages = await dbSAPPS.Image.count({
            where: filterConditions,
        });

        const countDocuments = await dbSAPPS.Document.count({
            where: filterConditions,
        });

        const countVideos = await dbSAPPS.Video.count({
            where: filterConditions,
        });

        return {
            countImages,
            countDocuments,
            countVideos,
            success: true,
            message: 'Images, Documents, and Videos has been loaded!'
        };
    } catch (error) {
        const errorMessage = error || 'Failed to retrieve images. Please try again later.';
        return {
            success: false,
            message: errorMessage
        };
    }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

        const developments = await dbSAPPS.Development.findAll({
            where: filterConditions,
            order: [['modified', 'DESC']],
            include: [
                { model: dbSAPPS.Aspect, as: 'aspects' },
                { model: dbSAPPS.Factor, as: 'factors' },
                { model: dbSAPPS.ProgressionTable, as: 'progressiontables' },
                { model: dbSAPPS.Level, as: 'levels' },
            ]
        });

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

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

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

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

        const countImages = await dbSAPPS.Image.count({
            where: filterConditions,
        });

        const countDocuments = await dbSAPPS.Document.count({
            where: filterConditions,
        });

        const countVideos = await dbSAPPS.Video.count({
            where: filterConditions,
        });

        return {
            countImages,
            countDocuments,
            countVideos,
            success: true,
            message: 'Images, Documents, and Videos has been loaded!'
        };
    } catch (error) {
        const errorMessage = error || 'Failed to retrieve images. Please try again later.';
        return {
            success: false,
            message: errorMessage
        };
    }
}

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

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

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

        const courses = await dbSAPPS.Course.findAll({
            where: filterConditions,
            order: [['modified', 'DESC']],
            include: [{
                model: dbSAPPS.CourseChild,
                as: 'coursechilds'
            }, {
                model: dbSAPPS.Image,
                as: 'images',
            }, {
                model: dbSAPPS.Document,
                as: 'documents',
            }, {
                model: dbSAPPS.Video,
                as: 'videos',
            }, {
                model: dbSAPPS.QuestionBank,
                as: 'questionbanks',
                include: [{
                    model: dbSAPPS.Question,
                    as: 'questions',
                    include: [{
                        model: dbSAPPS.Answer,
                        as: 'answers'
                    }]
                }]
            }, {
                model: dbSAPPS.App,
                as: 'apps',
                attributes: ['id'],
                required: false,
                subQuery: false
            }, {
                model: dbSAPPS.Development,
                as: 'developments',
                attributes: ['id'],
                required: false,
                subQuery: false,
            }],
        });

        if (!courses) {
            return {
                success: false,
                message: 'Course not found!'
            };
        }

        const developmentIds = courses.map(course => course.developments.map(development => development.id)).flat();
        const progressionTables = await dbSAPPS.ProgressionTable.findAll({
            where: {
                development_id: {
                    [Op.in]: developmentIds
                }
            }
        });
        courses.forEach(course => {
            course.dataValues.progressiontables = progressionTables.filter(pt => pt.development_id === course.developments[0].id);
        });

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

