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

module.exports = {
    filter,
    assignImagesToCourse,
    getAllCourseImage,
    deleteCourseImage
};

async function getImagesIdsByName(names) {
    const images = await dbSAPPS.Image.findAll({
        where: {
            display_name: names
        },
        attributes: ['id']
    });

    return images.map(image => image.id);
}

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

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

    try {
        const courseImages = await dbSAPPS.CourseImage.findAll({
            include: [
                {
                    model: dbSAPPS.Course,
                    as: 'course',
                },
                {
                    model: dbSAPPS.Image,
                    as: 'image',
                }
            ],
            where: filterConditions,
            order: [['updatedAt', 'DESC']],
        });

        const result = courseImages.reduce((acc, courseImage) => {
            const id = courseImage.id;
            const course_id = courseImage.course.id;
            const course_title = courseImage.course.title;
            const image_id = courseImage.image.id;
            const image_display_name = courseImage.image.display_name;

            const createdAt = courseImage.createdAt;
            const updatedAt = courseImage.updatedAt;

            let existingCourse = acc.find(item => item.course_id === course_id);
            if (!existingCourse) {
                existingCourse = {
                    id,
                    course_id,
                    course_title,
                    image_id,
                    image_display_name,
                    images: [],
                    imagesObject: {},
                    createdAt,
                    updatedAt
                };
                acc.push(existingCourse);
            }

            existingCourse.images.push(image_display_name);
            existingCourse.imagesObject = existingCourse.images.reduce((acc, display_name) => {
                acc[display_name] = true;
                return acc;
            }, {});

            return acc;
        }, []);

        return {
            courseImages: result,
            success: true,
            message: 'Course images 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 assignImagesToCourse(params) {
    const transaction = await dbSAPPS.sequelize.transaction();
    try {
        const { courseId, lastUsedCourseId, imageNames, update } = params;
        if (!courseId || !Array.isArray(imageNames) || imageNames.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 courseImage = await dbSAPPS.CourseImage.findOne({ where: { course_id: courseId } });
        if (courseImage && update === false) {
            await transaction.rollback();
            return { success: false, message: 'Course is already assigned to an image, please update the assignment if necessary.' };
        }

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

        const imageIds = await getImagesIdsByName(imageNames);

        await dbSAPPS.CourseImage.destroy({ where: { course_id: courseId }, transaction });
        await dbSAPPS.CourseImage.bulkCreate(
            imageIds.map(imageId => ({
                course_id: courseId,
                image_id: imageId
            })),
            { transaction }
        );
        await transaction.commit();
        return {
            success: true,
            message: 'Images have been assigned to the course!'
        };
    } catch (error) {
        await transaction.rollback();
        const errorMessage = error.message || 'Failed to assign images to the course.';
        return { success: false, message: errorMessage };
    }
}


async function getAllCourseImage() {
    try {
        const courseImages = await dbSAPPS.CourseImage.findAll({
            include: [
                {
                    model: dbSAPPS.Course,
                    as: 'course',
                },
                {
                    model: dbSAPPS.Image,
                    as: 'image',
                },
            ],
            order: [['updatedAt', 'DESC']],
        });

        const result = courseImages.reduce((acc, courseImage) => {
            const id = courseImage.course.id;
            const course_id = courseImage.course.id;
            const course_title = courseImage.course.title;
            const course_description = courseImage.course.description;
            const image_id = courseImage.image.id;
            const image_display_name = courseImage.image.display_name;

            const createdAt = courseImage.createdAt;
            const updatedAt = courseImage.updatedAt;

            let existingCourse = acc.find(item => item.course_id === course_id);
            if (!existingCourse) {
                existingCourse = {
                    id,
                    course_id,
                    course_title,
                    course_description,
                    image_id,
                    image_display_name,
                    images: [],
                    imagesObject: {},
                    createdAt,
                    updatedAt
                };
                acc.push(existingCourse);
            }

            existingCourse.images.push(image_display_name);
            existingCourse.imagesObject = existingCourse.images.reduce((acc, display_name) => {
                acc[display_name] = true;
                return acc;
            }, {});

            return acc;
        }, []);

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

async function deleteCourseImage(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 courseImage = await dbSAPPS.CourseImage.findAll({
            where: { course_id: id },
            transaction
        });

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

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

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


