
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Submission_gradesDBApi {
    

    
    static async create(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const submission_grades = await db.submission_grades.create(
            {
                id: data.id || undefined,
        
        graded_at: data.graded_at
        ||
        null
            ,
            
        total_score: data.total_score
        ||
        null
            ,
            
        max_score_snapshot: data.max_score_snapshot
        ||
        null
            ,
            
        grade_status: data.grade_status
        ||
        null
            ,
            
        teacher_feedback: data.teacher_feedback
        ||
        null
            ,
            
        returned_to_student: data.returned_to_student
        ||
        false
        
            ,
            
        returned_at: data.returned_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await submission_grades.setSubmission( data.submission || null, {
            transaction,
        });
        
        await submission_grades.setGraded_by_teacher( data.graded_by_teacher || null, {
            transaction,
        });
        
        await submission_grades.setSchools( data.schools || null, {
            transaction,
        });
        

        

        

        return submission_grades;
    }
    

    static async bulkImport(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        // Prepare data - wrapping individual data transformations in a map() method
        const submission_gradesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                graded_at: item.graded_at
            ||
            null
            ,
            
                total_score: item.total_score
            ||
            null
            ,
            
                max_score_snapshot: item.max_score_snapshot
            ||
            null
            ,
            
                grade_status: item.grade_status
            ||
            null
            ,
            
                teacher_feedback: item.teacher_feedback
            ||
            null
            ,
            
                returned_to_student: item.returned_to_student
            ||
            false
        
            ,
            
                returned_at: item.returned_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const submission_grades = await db.submission_grades.bulkCreate(submission_gradesData, { transaction });

        // For each item created, replace relation files
        

        return submission_grades;
    }

    static async update(id, data,  options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;
        const globalAccess = currentUser.app_role?.globalAccess;

        const submission_grades = await db.submission_grades.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.graded_at !== undefined) updatePayload.graded_at = data.graded_at;
        
        
        if (data.total_score !== undefined) updatePayload.total_score = data.total_score;
        
        
        if (data.max_score_snapshot !== undefined) updatePayload.max_score_snapshot = data.max_score_snapshot;
        
        
        if (data.grade_status !== undefined) updatePayload.grade_status = data.grade_status;
        
        
        if (data.teacher_feedback !== undefined) updatePayload.teacher_feedback = data.teacher_feedback;
        
        
        if (data.returned_to_student !== undefined) updatePayload.returned_to_student = data.returned_to_student;
        
        
        if (data.returned_at !== undefined) updatePayload.returned_at = data.returned_at;
        
        
        updatePayload.updatedById = currentUser.id;

        await submission_grades.update(updatePayload, {transaction});

        
        
        if (data.submission !== undefined) {
            await submission_grades.setSubmission(
              
              data.submission,
              
              { transaction }
            );
        }
        
        if (data.graded_by_teacher !== undefined) {
            await submission_grades.setGraded_by_teacher(
              
              data.graded_by_teacher,
              
              { transaction }
            );
        }
        
        if (data.schools !== undefined) {
            await submission_grades.setSchools(
              
              data.schools,
              
              { transaction }
            );
        }
        

        
        

        

        return submission_grades;
    }

    static async deleteByIds(ids, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const submission_grades = await db.submission_grades.findAll({
            where: {
                id: {
                    [Op.in]: ids,
                },
            },
            transaction,
        });

        await db.sequelize.transaction(async (transaction) => {
            for (const record of submission_grades) {
                await record.update(
                    {deletedBy: currentUser.id},
                    {transaction}
                );
            }
            for (const record of submission_grades) {
                await record.destroy({transaction});
            }
        });


        return submission_grades;
    }

    static async remove(id, options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;

        const submission_grades = await db.submission_grades.findByPk(id, options);

        await submission_grades.update({
            deletedBy: currentUser.id
        }, {
            transaction,
        });

        await submission_grades.destroy({
            transaction
        });

        return submission_grades;
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;

        const submission_grades = await db.submission_grades.findOne(
            { where },
            { transaction },
        );

        if (!submission_grades) {
            return submission_grades;
        }

        const output = submission_grades.get({plain: true});

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.rubric_scores_submission_grade = await submission_grades.getRubric_scores_submission_grade({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.submission = await submission_grades.getSubmission({
            transaction
        });
        
        
        output.graded_by_teacher = await submission_grades.getGraded_by_teacher({
            transaction
        });
        
        
        output.schools = await submission_grades.getSchools({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userSchools = (user && user.schools?.id) || null;
        

        
        if (userSchools) {
            if (options?.currentUser?.schoolsId) {
                where.schoolsId = options.currentUser.schoolsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.homework_submissions,
        as: 'submission',
        
        where: filter.submission ? {
          [Op.or]: [
            { id: { [Op.in]: filter.submission.split('|').map(term => Utils.uuid(term)) } },
            {
              submission_status: {
                [Op.or]: filter.submission.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'graded_by_teacher',
        
        where: filter.graded_by_teacher ? {
          [Op.or]: [
            { id: { [Op.in]: filter.graded_by_teacher.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.graded_by_teacher.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.schools,
        as: 'schools',
        
      },



    ];

        if (filter) {
            if (filter.id) {
                where = {
                    ...where,
                    ['id']: Utils.uuid(filter.id),
                };
            }

            
            if (filter.teacher_feedback) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'submission_grades',
                        'teacher_feedback',
                        filter.teacher_feedback,
                    ),
                };
            }
            

            
            

            
            if (filter.graded_atRange) {
                const [start, end] = filter.graded_atRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    graded_at: {
                    ...where.graded_at,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    graded_at: {
                    ...where.graded_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.total_scoreRange) {
                const [start, end] = filter.total_scoreRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    total_score: {
                    ...where.total_score,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    total_score: {
                    ...where.total_score,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.max_score_snapshotRange) {
                const [start, end] = filter.max_score_snapshotRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    max_score_snapshot: {
                    ...where.max_score_snapshot,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    max_score_snapshot: {
                    ...where.max_score_snapshot,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.returned_atRange) {
                const [start, end] = filter.returned_atRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    returned_at: {
                    ...where.returned_at,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    returned_at: {
                    ...where.returned_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.grade_status) {
                where = {
                    ...where,
                grade_status: filter.grade_status,
            };
            }
            
            if (filter.returned_to_student) {
                where = {
                    ...where,
                returned_to_student: filter.returned_to_student,
            };
            }
            


      

      

      
      if (filter.schools) {
        const listItems = filter.schools.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          schoolsId: {[Op.or]: listItems}
        };
      }
      



            if (filter.createdAtRange) {
                const [start, end] = filter.createdAtRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.gte]: start,
                        },
                    };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.lte]: end,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.schoolsId;
        }
        

        const queryOptions = {
            where,
            include,
            distinct: true,
            order: filter.field && filter.sort
                ? [[filter.field, filter.sort]]
                : [['createdAt', 'desc']],
            transaction: options?.transaction,
            logging: console.log
        };

        if (!options?.countOnly) {
            queryOptions.limit = limit ? Number(limit) : undefined;
            queryOptions.offset = offset ? Number(offset) : undefined;
        }

        try {
            const { rows, count } = await db.submission_grades.findAndCountAll(queryOptions);

            return {
                rows: options?.countOnly ? [] : rows,
                count: count
            };
        } catch (error) {
            console.error('Error executing query:', error);
            throw error;
        }
    }

    static async findAllAutocomplete(query, limit, offset,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'submission_grades',
                        'grade_status',
                        query,
                    ),
                ],
            };
        }

        const records = await db.submission_grades.findAll({
            attributes: [ 'id', 'grade_status' ],
            where,
            limit: limit ? Number(limit) : undefined,
            offset: offset ? Number(offset) : undefined,
            orderBy: [['grade_status', 'ASC']],
        });

        return records.map((record) => ({
            id: record.id,
            label: record.grade_status,
        }));
    }

    
};

