
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,
        
        comment: data.comment
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        grade_value: data.grade_value
        ||
        null
            ,
            
        teacher_feedback: data.teacher_feedback
        ||
        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 FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.assignment_submissions.getTableName(),
                belongsToColumn: 'files',
                belongsToId: assignment_submissions.id,
            },
            data.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,
                
                comment: item.comment
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                grade_value: item.grade_value
            ||
            null
            ,
            
                teacher_feedback: item.teacher_feedback
            ||
            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: 'files',
                    belongsToId: assignment_submissions[i].id,
                },
                data[i].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 assignment_submissions = await db.assignment_submissions.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.comment !== undefined) updatePayload.comment = data.comment;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.grade_value !== undefined) updatePayload.grade_value = data.grade_value;
        
        
        if (data.teacher_feedback !== undefined) updatePayload.teacher_feedback = data.teacher_feedback;
        
        
        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 }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.assignment_submissions.getTableName(),
                belongsToColumn: 'files',
                belongsToId: assignment_submissions.id,
            },
            data.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.files = await assignment_submissions.getFiles({
            transaction
        });
        
        

        return output;
    }

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

        

        

        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)) } },
            {
              full_name: {
                [Op.or]: filter.student.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

            
            if (filter.comment) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'assignment_submissions',
                        'comment',
                        filter.comment,
                    ),
                };
            }
            
            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.grade_valueRange) {
                const [start, end] = filter.grade_valueRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    grade_value: {
                    ...where.grade_value,
                            [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.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,
                        },
                    };
                }
            }
        }
        

        

        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, ) {
        let where = {};
        
        

        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,
        }));
    }

    
};

