
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 Assignment_submissionsDBApi {
    

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

        const assignment_submissions = await db.assignment_submissions.create(
            {
                id: data.id || undefined,
        
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        answer_text: data.answer_text
        ||
        null
            ,
            
        score: data.score
        ||
        null
            ,
            
        teacher_feedback: data.teacher_feedback
        ||
        null
            ,
            
        graded_at: data.graded_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await assignment_submissions.setAssignment( data.assignment || null, {
            transaction,
        });
        
        await assignment_submissions.setStudent( data.student || null, {
            transaction,
        });
        
        await assignment_submissions.setGraded_by( data.graded_by || null, {
            transaction,
        });
        
        await assignment_submissions.setSchools( data.schools || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.assignment_submissions.getTableName(),
                belongsToColumn: 'answer_files',
                belongsToId: assignment_submissions.id,
            },
            data.answer_files,
            options,
        );
        

        return assignment_submissions;
    }
    

    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 assignment_submissionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                answer_text: item.answer_text
            ||
            null
            ,
            
                score: item.score
            ||
            null
            ,
            
                teacher_feedback: item.teacher_feedback
            ||
            null
            ,
            
                graded_at: item.graded_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < assignment_submissions.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.assignment_submissions.getTableName(),
                    belongsToColumn: 'answer_files',
                    belongsToId: assignment_submissions[i].id,
                },
                data[i].answer_files,
                options,
            );
        }
        

        return assignment_submissions;
    }

    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 assignment_submissions = await db.assignment_submissions.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.answer_text !== undefined) updatePayload.answer_text = data.answer_text;
        
        
        if (data.score !== undefined) updatePayload.score = data.score;
        
        
        if (data.teacher_feedback !== undefined) updatePayload.teacher_feedback = data.teacher_feedback;
        
        
        if (data.graded_at !== undefined) updatePayload.graded_at = data.graded_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.assignment !== undefined) {
            await assignment_submissions.setAssignment(
              
              data.assignment,
              
              { transaction }
            );
        }
        
        if (data.student !== undefined) {
            await assignment_submissions.setStudent(
              
              data.student,
              
              { transaction }
            );
        }
        
        if (data.graded_by !== undefined) {
            await assignment_submissions.setGraded_by(
              
              data.graded_by,
              
              { transaction }
            );
        }
        
        if (data.schools !== undefined) {
            await assignment_submissions.setSchools(
              
              data.schools,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.assignment_submissions.getTableName(),
                belongsToColumn: 'answer_files',
                belongsToId: assignment_submissions.id,
            },
            data.answer_files,
            options,
        );
        

        return assignment_submissions;
    }

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

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

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


        return assignment_submissions;
    }

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

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

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

        await assignment_submissions.destroy({
            transaction
        });

        return assignment_submissions;
    }

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

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

        if (!assignment_submissions) {
            return assignment_submissions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.assignment = await assignment_submissions.getAssignment({
            transaction
        });
        
        
        output.student = await assignment_submissions.getStudent({
            transaction
        });
        
        
        output.answer_files = await assignment_submissions.getAnswer_files({
            transaction
        });
        
        
        output.graded_by = await assignment_submissions.getGraded_by({
            transaction
        });
        
        
        output.schools = await assignment_submissions.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.assignments,
        as: 'assignment',
        
        where: filter.assignment ? {
          [Op.or]: [
            { id: { [Op.in]: filter.assignment.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.assignment.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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



      {
        model: db.file,
        as: 'answer_files',
      },

    ];

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

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

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    score: {
                    ...where.score,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

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


      

      

      

      
      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.assignment_submissions.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(
                        'assignment_submissions',
                        'status',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

