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

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

        const homework_extensions = await db.homework_extensions.create(
            {
                id: data.id || undefined,
        
        extension_scope: data.extension_scope
        ||
        null
            ,
            
        extended_due_at: data.extended_due_at
        ||
        null
            ,
            
        extended_late_until_at: data.extended_late_until_at
        ||
        null
            ,
            
        reason: data.reason
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await homework_extensions.setHomework( data.homework || null, {
            transaction,
        });
        
        await homework_extensions.setCreated_by_user( data.created_by_user || null, {
            transaction,
        });
        
        await homework_extensions.setSchools( data.schools || null, {
            transaction,
        });
        

        
        await homework_extensions.setStudents(data.students || [], {
            transaction,
        });
        

        

        return homework_extensions;
    }
    

    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_extensionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                extension_scope: item.extension_scope
            ||
            null
            ,
            
                extended_due_at: item.extended_due_at
            ||
            null
            ,
            
                extended_late_until_at: item.extended_late_until_at
            ||
            null
            ,
            
                reason: item.reason
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return homework_extensions;
    }

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


        

        const updatePayload = {};
        
        if (data.extension_scope !== undefined) updatePayload.extension_scope = data.extension_scope;
        
        
        if (data.extended_due_at !== undefined) updatePayload.extended_due_at = data.extended_due_at;
        
        
        if (data.extended_late_until_at !== undefined) updatePayload.extended_late_until_at = data.extended_late_until_at;
        
        
        if (data.reason !== undefined) updatePayload.reason = data.reason;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.homework !== undefined) {
            await homework_extensions.setHomework(
              
              data.homework,
              
              { transaction }
            );
        }
        
        if (data.created_by_user !== undefined) {
            await homework_extensions.setCreated_by_user(
              
              data.created_by_user,
              
              { transaction }
            );
        }
        
        if (data.schools !== undefined) {
            await homework_extensions.setSchools(
              
              data.schools,
              
              { transaction }
            );
        }
        

        
        
        if (data.students !== undefined) {
            await homework_extensions.setStudents(data.students, { transaction });
        }
        

        

        return homework_extensions;
    }

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

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

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


        return homework_extensions;
    }

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

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

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

        await homework_extensions.destroy({
            transaction
        });

        return homework_extensions;
    }

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

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

        if (!homework_extensions) {
            return homework_extensions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.homework = await homework_extensions.getHomework({
            transaction
        });
        
        
        output.students = await homework_extensions.getStudents({
            transaction
        });
        
        
        output.created_by_user = await homework_extensions.getCreated_by_user({
            transaction
        });
        
        
        output.schools = await homework_extensions.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: 'created_by_user',
        
        where: filter.created_by_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.created_by_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.created_by_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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


      {
        model: db.users,
        as: 'students',
        required: false,
      },


    ];

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

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

            
            

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

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

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

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

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

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

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


      

      

      
      if (filter.schools) {
        const listItems = filter.schools.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          schoolsId: {[Op.or]: listItems}
        };
      }
      


      if (filter.students) {
        const searchTerms = filter.students.split('|');

        include = [
          {
            model: db.users,
            as: 'students_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  firstName: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


            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_extensions.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_extensions',
                        'reason',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

