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

module.exports = {
    filter,
    assignDocumentsToCourse,
    getAllCourseDocument,
    deleteCourseDocument
};

async function getDocumentsIdsByName(names) {
    const documents = await dbSAPPS.Document.findAll({
        where: {
            display_name: names
        },
        attributes: ['id']
    });

    return documents.map(document => document.id);
}

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

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

    try {
        const courseDocuments = await dbSAPPS.CourseDocument.findAll({
            include: [
                {
                    model: dbSAPPS.Course,
                    as: 'course',
                },
                {
                    model: dbSAPPS.Document,
                    as: 'document',
                }
            ],
            where: filterConditions,
            order: [['updatedAt', 'DESC']],
        });

        const result = courseDocuments.reduce((acc, courseDocument) => {
            const id = courseDocument.id;
            const course_id = courseDocument.course.id;
            const course_title = courseDocument.course.title;
            const document_id = courseDocument.document.id;
            const document_display_name = courseDocument.document.display_name;

            const createdAt = courseDocument.createdAt;
            const updatedAt = courseDocument.updatedAt;

            let existingCourse = acc.find(item => item.course_id === course_id);
            if (!existingCourse) {
                existingCourse = {
                    id,
                    course_id,
                    course_title,
                    document_id,
                    document_display_name,
                    documents: [],
                    documentsObject: {},
                    createdAt,
                    updatedAt
                };
                acc.push(existingCourse);
            }

            existingCourse.documents.push(document_display_name);
            existingCourse.documentsObject = existingCourse.documents.reduce((acc, display_name) => {
                acc[display_name] = true;
                return acc;
            }, {});

            return acc;
        }, []);

        return {
            courseDocuments: result,
            success: true,
            message: 'Course documents 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 assignDocumentsToCourse(params) {
    const transaction = await dbSAPPS.sequelize.transaction();
    try {
        const { courseId, lastUsedCourseId, documentNames, update } = params;
        if (!courseId || !Array.isArray(documentNames) || documentNames.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 courseDocument = await dbSAPPS.CourseDocument.findOne({ where: { course_id: courseId } });
        if (courseDocument && update === false) {
            await transaction.rollback();
            return { success: false, message: 'Course is already assigned to a document, please update the assignment if necessary.' };
        }

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

        const documentIds = await getDocumentsIdsByName(documentNames);

        await dbSAPPS.CourseDocument.destroy({ where: { course_id: courseId }, transaction });
        await dbSAPPS.CourseDocument.bulkCreate(
            documentIds.map(documentId => ({
                course_id: courseId,
                document_id: documentId
            })),
            { transaction }
        );
        await transaction.commit();
        return {
            success: true,
            message: 'Documents have been assigned to the course!'
        };
    } catch (error) {
        await transaction.rollback();
        const errorMessage = error.message || 'Failed to assign documents to the course.';
        return { success: false, message: errorMessage };
    }
}

async function getAllCourseDocument() {
    try {
        const courseDocuments = await dbSAPPS.CourseDocument.findAll({
            include: [
                {
                    model: dbSAPPS.Course,
                    as: 'course',
                },
                {
                    model: dbSAPPS.Document,
                    as: 'document',
                },
            ],
            order: [['updatedAt', 'DESC']],
        });

        const result = courseDocuments.reduce((acc, courseDocument) => {
            const id = courseDocument.course.id;
            const course_id = courseDocument.course.id;
            const course_title = courseDocument.course.title;
            const course_description = courseDocument.course.description;
            const document_id = courseDocument.document.id;
            const document_display_name = courseDocument.document.display_name;

            const createdAt = courseDocument.createdAt;
            const updatedAt = courseDocument.updatedAt;

            let existingCourse = acc.find(item => item.course_id === course_id);
            if (!existingCourse) {
                existingCourse = {
                    id,
                    course_id,
                    course_title,
                    course_description,
                    document_id,
                    document_display_name,
                    documents: [],
                    documentsObject: {},
                    createdAt,
                    updatedAt
                };
                acc.push(existingCourse);
            }

            existingCourse.documents.push(document_display_name);
            existingCourse.documentsObject = existingCourse.documents.reduce((acc, display_name) => {
                acc[display_name] = true;
                return acc;
            }, {});

            return acc;
        }, []);

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

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

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

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

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

