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

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

        const homework_submissions = await db.homework_submissions.create(
            {
                id: data.id || undefined,
        
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        submission_status: data.submission_status
        ||
        null
            ,
            
        submission_text: data.submission_text
        ||
        null
            ,
            
        face_verified_for_submission: data.face_verified_for_submission
        ||
        false
        
            ,
            
        face_verified_at: data.face_verified_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await homework_submissions.setHomework( data.homework || null, {
            transaction,
        });
        
        await homework_submissions.setStudent( data.student || null, {
            transaction,
        });
        
        await homework_submissions.setSchools( data.schools || null, {
            transaction,
        });
        

        

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

        return homework_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 homework_submissionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                submission_status: item.submission_status
            ||
            null
            ,
            
                submission_text: item.submission_text
            ||
            null
            ,
            
                face_verified_for_submission: item.face_verified_for_submission
            ||
            false
        
            ,
            
                face_verified_at: item.face_verified_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

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


        

        const updatePayload = {};
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.submission_status !== undefined) updatePayload.submission_status = data.submission_status;
        
        
        if (data.submission_text !== undefined) updatePayload.submission_text = data.submission_text;
        
        
        if (data.face_verified_for_submission !== undefined) updatePayload.face_verified_for_submission = data.face_verified_for_submission;
        
        
        if (data.face_verified_at !== undefined) updatePayload.face_verified_at = data.face_verified_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.homework !== undefined) {
            await homework_submissions.setHomework(
              
              data.homework,
              
              { transaction }
            );
        }
        
        if (data.student !== undefined) {
            await homework_submissions.setStudent(
              
              data.student,
              
              { transaction }
            );
        }
        
        if (data.schools !== undefined) {
            await homework_submissions.setSchools(
              
              data.schools,
              
              { transaction }
            );
        }
        

        
        

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

        return homework_submissions;
    }

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

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

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


        return homework_submissions;
    }

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

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

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

        await homework_submissions.destroy({
            transaction
        });

        return homework_submissions;
    }

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

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

        if (!homework_submissions) {
            return homework_submissions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.submission_grades_submission = await homework_submissions.getSubmission_grades_submission({
            transaction
        });
        
        
        
        
        
        
        
        
        output.notifications_submission = await homework_submissions.getNotifications_submission({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.homework = await homework_submissions.getHomework({
            transaction
        });
        
        
        output.student = await homework_submissions.getStudent({
            transaction
        });
        
        
        output.submission_files = await homework_submissions.getSubmission_files({
            transaction
        });
        
        
        output.evidence_images = await homework_submissions.getEvidence_images({
            transaction
        });
        
        
        output.schools = await homework_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.homeworks,
        as: 'homework',
        
        where: filter.homework ? {
          [Op.or]: [
            { id: { [Op.in]: filter.homework.split('|').map(term => Utils.uuid(term)) } },
            {
              homework_title: {
                [Op.or]: filter.homework.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



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

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

    ];

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

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

            
            

            
            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.face_verified_atRange) {
                const [start, end] = filter.face_verified_atRange;

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

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

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

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


      

      

      
      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.homework_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(
                        'homework_submissions',
                        'submission_status',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

