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

module.exports = {
    filter,
    assignVideosToCourse,
    getAllCourseVideo,
    deleteCourseVideo
};

async function getVideosIdsByName(names) {
    const videos = await dbSAPPS.Video.findAll({
        where: {
            display_name: names
        },
        attributes: ['id']
    });

    return videos.map(video => video.id);
}

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

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

    try {
        const courseVideos = await dbSAPPS.CourseVideo.findAll({
            include: [
                {
                    model: dbSAPPS.Course,
                    as: 'course',
                },
                {
                    model: dbSAPPS.Video,
                    as: 'video',
                }
            ],
            where: filterConditions,
            order: [['updatedAt', 'DESC']],
        });

        const result = courseVideos.reduce((acc, courseVideo) => {
            const id = courseVideo.id;
            const course_id = courseVideo.course.id;
            const course_title = courseVideo.course.title;
            const video_id = courseVideo.video.id;
            const video_display_name = courseVideo.video.display_name;

            const createdAt = courseVideo.createdAt;
            const updatedAt = courseVideo.updatedAt;

            let existingCourse = acc.find(item => item.course_id === course_id);
            if (!existingCourse) {
                existingCourse = {
                    id,
                    course_id,
                    course_title,
                    video_id,
                    video_display_name,
                    videos: [],
                    videosObject: {},
                    createdAt,
                    updatedAt
                };
                acc.push(existingCourse);
            }

            existingCourse.videos.push(video_display_name);
            existingCourse.videosObject = existingCourse.videos.reduce((acc, display_name) => {
                acc[display_name] = true;
                return acc;
            }, {});

            return acc;
        }, []);

        return {
            courseVideos: result,
            success: true,
            message: 'Course videos 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 assignVideosToCourse(params) {
    const transaction = await dbSAPPS.sequelize.transaction();
    try {
        const { courseId, lastUsedCourseId, videoNames, update } = params;
        if (!courseId || !Array.isArray(videoNames) || videoNames.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 courseVideo = await dbSAPPS.CourseVideo.findOne({ where: { course_id: courseId } });
        if (courseVideo && update === false) {
            await transaction.rollback();
            return { success: false, message: 'Course is already assigned to a video, please update the assignment if necessary.' };
        }

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

        const videoIds = await getVideosIdsByName(videoNames);

        await dbSAPPS.CourseVideo.destroy({ where: { course_id: courseId }, transaction });
        await dbSAPPS.CourseVideo.bulkCreate(
            videoIds.map(videoId => ({
                course_id: courseId,
                video_id: videoId
            })),
            { transaction }
        );
        await transaction.commit();
        return {
            success: true,
            message: 'Videos have been assigned to the course!'
        };
    } catch (error) {
        await transaction.rollback();
        const errorMessage = error.message || 'Failed to assign videos to the course.';
        return { success: false, message: errorMessage };
    }
}


async function getAllCourseVideo() {
    try {
        const courseVideos = await dbSAPPS.CourseVideo.findAll({
            include: [
                {
                    model: dbSAPPS.Course,
                    as: 'course',
                },
                {
                    model: dbSAPPS.Video,
                    as: 'video',
                },
            ],
            order: [['updatedAt', 'DESC']],
        });

        const result = courseVideos.reduce((acc, courseVideo) => {
            const id = courseVideo.course.id;
            const course_id = courseVideo.course.id;
            const course_title = courseVideo.course.title;
            const course_description = courseVideo.course.description;
            const video_id = courseVideo.video.id;
            const video_display_name = courseVideo.video.display_name;

            const createdAt = courseVideo.createdAt;
            const updatedAt = courseVideo.updatedAt;

            let existingCourse = acc.find(item => item.course_id === course_id);
            if (!existingCourse) {
                existingCourse = {
                    id,
                    course_id,
                    course_title,
                    course_description,
                    video_id,
                    video_display_name,
                    videos: [],
                    videosObject: {},
                    createdAt,
                    updatedAt
                };
                acc.push(existingCourse);
            }

            existingCourse.videos.push(video_display_name);
            existingCourse.videosObject = existingCourse.videos.reduce((acc, display_name) => {
                acc[display_name] = true;
                return acc;
            }, {});

            return acc;
        }, []);

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

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

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

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

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