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

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

        const homeworks = await db.homeworks.create(
            {
                id: data.id || undefined,
        
        homework_title: data.homework_title
        ||
        null
            ,
            
        homework_description: data.homework_description
        ||
        null
            ,
            
        assigned_at: data.assigned_at
        ||
        null
            ,
            
        due_at: data.due_at
        ||
        null
            ,
            
        late_until_at: data.late_until_at
        ||
        null
            ,
            
        homework_status: data.homework_status
        ||
        null
            ,
            
        max_score: data.max_score
        ||
        null
            ,
            
        allow_late: data.allow_late
        ||
        false
        
            ,
            
        requires_face_verification: data.requires_face_verification
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await homeworks.setClassroom( data.classroom || null, {
            transaction,
        });
        
        await homeworks.setSubject( data.subject || null, {
            transaction,
        });
        
        await homeworks.setTeacher( data.teacher || null, {
            transaction,
        });
        
        await homeworks.setSchools( data.schools || null, {
            transaction,
        });
        

        

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

        return homeworks;
    }
    

    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 homeworksData = data.map((item, index) => ({
                id: item.id || undefined,
                
                homework_title: item.homework_title
            ||
            null
            ,
            
                homework_description: item.homework_description
            ||
            null
            ,
            
                assigned_at: item.assigned_at
            ||
            null
            ,
            
                due_at: item.due_at
            ||
            null
            ,
            
                late_until_at: item.late_until_at
            ||
            null
            ,
            
                homework_status: item.homework_status
            ||
            null
            ,
            
                max_score: item.max_score
            ||
            null
            ,
            
                allow_late: item.allow_late
            ||
            false
        
            ,
            
                requires_face_verification: item.requires_face_verification
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return homeworks;
    }

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


        

        const updatePayload = {};
        
        if (data.homework_title !== undefined) updatePayload.homework_title = data.homework_title;
        
        
        if (data.homework_description !== undefined) updatePayload.homework_description = data.homework_description;
        
        
        if (data.assigned_at !== undefined) updatePayload.assigned_at = data.assigned_at;
        
        
        if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
        
        
        if (data.late_until_at !== undefined) updatePayload.late_until_at = data.late_until_at;
        
        
        if (data.homework_status !== undefined) updatePayload.homework_status = data.homework_status;
        
        
        if (data.max_score !== undefined) updatePayload.max_score = data.max_score;
        
        
        if (data.allow_late !== undefined) updatePayload.allow_late = data.allow_late;
        
        
        if (data.requires_face_verification !== undefined) updatePayload.requires_face_verification = data.requires_face_verification;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.classroom !== undefined) {
            await homeworks.setClassroom(
              
              data.classroom,
              
              { transaction }
            );
        }
        
        if (data.subject !== undefined) {
            await homeworks.setSubject(
              
              data.subject,
              
              { transaction }
            );
        }
        
        if (data.teacher !== undefined) {
            await homeworks.setTeacher(
              
              data.teacher,
              
              { transaction }
            );
        }
        
        if (data.schools !== undefined) {
            await homeworks.setSchools(
              
              data.schools,
              
              { transaction }
            );
        }
        

        
        

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

        return homeworks;
    }

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

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

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


        return homeworks;
    }

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

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

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

        await homeworks.destroy({
            transaction
        });

        return homeworks;
    }

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

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

        if (!homeworks) {
            return homeworks;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        output.homework_rubrics_homework = await homeworks.getHomework_rubrics_homework({
            transaction
        });
        
        
        output.homework_extensions_homework = await homeworks.getHomework_extensions_homework({
            transaction
        });
        
        
        output.homework_submissions_homework = await homeworks.getHomework_submissions_homework({
            transaction
        });
        
        
        
        
        
        output.gradebook_columns_homework = await homeworks.getGradebook_columns_homework({
            transaction
        });
        
        
        
        
        
        output.notifications_homework = await homeworks.getNotifications_homework({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.classroom = await homeworks.getClassroom({
            transaction
        });
        
        
        output.subject = await homeworks.getSubject({
            transaction
        });
        
        
        output.teacher = await homeworks.getTeacher({
            transaction
        });
        
        
        output.attachments = await homeworks.getAttachments({
            transaction
        });
        
        
        output.schools = await homeworks.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.classrooms,
        as: 'classroom',
        
        where: filter.classroom ? {
          [Op.or]: [
            { id: { [Op.in]: filter.classroom.split('|').map(term => Utils.uuid(term)) } },
            {
              classroom_name: {
                [Op.or]: filter.classroom.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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



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

    ];

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

            
            if (filter.homework_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'homeworks',
                        'homework_title',
                        filter.homework_title,
                    ),
                };
            }
            
            if (filter.homework_description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'homeworks',
                        'homework_description',
                        filter.homework_description,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            due_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    late_until_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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

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

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

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

            
            if (filter.homework_status) {
                where = {
                    ...where,
                homework_status: filter.homework_status,
            };
            }
            
            if (filter.allow_late) {
                where = {
                    ...where,
                allow_late: filter.allow_late,
            };
            }
            
            if (filter.requires_face_verification) {
                where = {
                    ...where,
                requires_face_verification: filter.requires_face_verification,
            };
            }
            


      

      

      

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

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

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

    
};

