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

module.exports = {
    filter,
    assignDevelopmentsToCourse,
    getAllCourseDevelopment,
    deleteCourseDevelopment
};

async function getDevelopmentsIdsByName(names) {
    const developments = await dbSAPPS.Development.findAll({
        where: {
            title: names
        },
        attributes: ['id']
    });

    return developments.map(development => development.id);
}

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

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

    try {
        const courseDevelopments = await dbSAPPS.CourseDevelopment.findAll({
            include: [
                {
                    model: dbSAPPS.Course,
                    as: 'course',
                },
                {
                    model: dbSAPPS.Development,
                    as: 'development',
                }
            ],
            where: filterConditions,
            order: [['updatedAt', 'DESC']],
        });

        const result = courseDevelopments.reduce((acc, courseDevelopment) => {
            const id = courseDevelopment.id;
            const course_id = courseDevelopment.course.id;
            const course_title = courseDevelopment.course.title;
            const development_id = courseDevelopment.development.id;
            const development_title = courseDevelopment.development.title;

            const createdAt = courseDevelopment.createdAt;
            const updatedAt = courseDevelopment.updatedAt;

            let existingCourse = acc.find(item => item.course_id === course_id);
            if (!existingCourse) {
                existingCourse = {
                    id,
                    course_id,
                    course_title,
                    development_id,
                    development_title,
                    developments: [],
                    developmentsObject: {},
                    createdAt,
                    updatedAt
                };
                acc.push(existingCourse);
            }

            existingCourse.developments.push(development_title);
            existingCourse.developmentsObject = existingCourse.developments.reduce((acc, title) => {
                acc[title] = true;
                return acc;
            }, {});

            return acc;
        }, []);

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

async function assignDevelopmentsToCourse(params) {
    const transaction = await dbSAPPS.sequelize.transaction();
    try {
        const { courseId, lastUsedCourseId, developmentNames, update } = params;
        if (!courseId || !Array.isArray(developmentNames) || developmentNames.length === 0) {
            return {
                success: false,
                message: 'Invalid input. Please ensure that all required fields are provided in the correct format.'
            };
        }

        const course = await dbSAPPS.Course.findByPk(courseId, { transaction });
        if (!course) {
            await transaction.rollback();
            return { success: false, message: 'Course not found!' };
        }

        const courseDevelopment = await dbSAPPS.CourseDevelopment.findOne({ where: { course_id: courseId } });
        if (courseDevelopment && update === false) {
            await transaction.rollback();
            return { success: false, message: 'Course is already assigned to a development, please update the assignment if necessary.' };
        }

        if (lastUsedCourseId && update === true) {
            const lastUse = await dbSAPPS.CourseDevelopment.findOne({ where: { course_id: lastUsedCourseId } });
            if (lastUse) {
                await lastUse.destroy({ transaction });
            }
        }

        const developmentIds = await getDevelopmentsIdsByName(developmentNames);

        await dbSAPPS.CourseDevelopment.destroy({ where: { course_id: courseId }, transaction });
        await dbSAPPS.CourseDevelopment.bulkCreate(
            developmentIds.map(developmentId => ({
                course_id: courseId,
                development_id: developmentId
            })),
            { transaction }
        );
        await transaction.commit();
        return {
            success: true,
            message: 'Developments have been assigned to the course!'
        };
    } catch (error) {
        await transaction.rollback();
        const errorMessage = error.message || 'Failed to assign developments to the course.';
        return { success: false, message: errorMessage };
    }
}

async function getAllCourseDevelopment() {
    try {
        const courseDevelopments = await dbSAPPS.CourseDevelopment.findAll({
            include: [
                {
                    model: dbSAPPS.Course,
                    as: 'course',
                },
                {
                    model: dbSAPPS.Development,
                    as: 'development',
                },
            ],
            order: [['updatedAt', 'DESC']],
        });

        const result = courseDevelopments.reduce((acc, courseDevelopment) => {
            const id = courseDevelopment.course.id;
            const course_id = courseDevelopment.course.id;
            const course_title = courseDevelopment.course.title;
            const course_description = courseDevelopment.course.description;
            const development_id = courseDevelopment.development.id;
            const development_title = courseDevelopment.development.title;

            const createdAt = courseDevelopment.createdAt;
            const updatedAt = courseDevelopment.updatedAt;

            let existingCourse = acc.find(item => item.course_id === course_id);
            if (!existingCourse) {
                existingCourse = {
                    id,
                    course_id,
                    course_title,
                    course_description,
                    development_id,
                    development_title,
                    developments: [],
                    developmentsObject: {},
                    createdAt,
                    updatedAt
                };
                acc.push(existingCourse);
            }

            existingCourse.developments.push(development_title);
            existingCourse.developmentsObject = existingCourse.developments.reduce((acc, title) => {
                acc[title] = true;
                return acc;
            }, {});

            return acc;
        }, []);

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

async function deleteCourseDevelopment(id) {
    const transaction = await dbSAPPS.sequelize.transaction();
    try {
        const course = await dbSAPPS.Course.findByPk(id, { transaction });
        if (!course) {
            await transaction.rollback();
            return { success: false, message: 'Course not found!' };
        }

        const courseDevelopment = await dbSAPPS.CourseDevelopment.findAll({
            where: { course_id: id },
            transaction
        });

        if (courseDevelopment.length === 0) {
            await transaction.rollback();
            return {
                success: false,
                message: 'Course has no associated development, so it was not deleted.'
            };
        }

        await dbSAPPS.CourseDevelopment.destroy({
            where: { course_id: id },
            transaction
        });

        await transaction.commit();
        return {
            success: true,
            message: 'Course and developments has been deleted!'
        };
    } catch (error) {
        await transaction.rollback();
        const errorMessage = error.message || 'Failed to delete Course and developments.';
        return { success: false, message: errorMessage };
    }
}


