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

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

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

        
        await submissions.setAssignment( data.assignment || null, {
            transaction,
        });
        
        await submissions.setStudent( data.student || null, {
            transaction,
        });
        

        

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

        return 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 submissionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                text_response: item.text_response
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                score: item.score
            ||
            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 submissions = await db.submissions.bulkCreate(submissionsData, { transaction });

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

        return submissions;
    }

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

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


        

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

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

        
        
        if (data.assignment !== undefined) {
            await submissions.setAssignment(
              
              data.assignment,
              
              { transaction }
            );
        }
        
        if (data.student !== undefined) {
            await submissions.setStudent(
              
              data.student,
              
              { transaction }
            );
        }
        

        
        

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

        return submissions;
    }

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

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

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


        return submissions;
    }

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

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

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

        await submissions.destroy({
            transaction
        });

        return submissions;
    }

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

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

        if (!submissions) {
            return submissions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.assignment = await submissions.getAssignment({
            transaction
        });
        
        
        output.student = await submissions.getStudent({
            transaction
        });
        
        
        output.files = await 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)) } },
            {
              student_number: {
                [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.text_response) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'submissions',
                        'text_response',
                        filter.text_response,
                    ),
                };
            }
            
            if (filter.teacher_feedback) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        '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.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.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(
                        'submissions',
                        'status',
                        query,
                    ),
                ],
            };
        }

        const records = await db.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,
        }));
    }

    
};

