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

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

        const homework_rubrics = await db.homework_rubrics.create(
            {
                id: data.id || undefined,
        
        criterion_title: data.criterion_title
        ||
        null
            ,
            
        criterion_description: data.criterion_description
        ||
        null
            ,
            
        criterion_max_score: data.criterion_max_score
        ||
        null
            ,
            
        sort_order: data.sort_order
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return homework_rubrics;
    }
    

    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_rubricsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                criterion_title: item.criterion_title
            ||
            null
            ,
            
                criterion_description: item.criterion_description
            ||
            null
            ,
            
                criterion_max_score: item.criterion_max_score
            ||
            null
            ,
            
                sort_order: item.sort_order
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return homework_rubrics;
    }

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


        

        const updatePayload = {};
        
        if (data.criterion_title !== undefined) updatePayload.criterion_title = data.criterion_title;
        
        
        if (data.criterion_description !== undefined) updatePayload.criterion_description = data.criterion_description;
        
        
        if (data.criterion_max_score !== undefined) updatePayload.criterion_max_score = data.criterion_max_score;
        
        
        if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return homework_rubrics;
    }

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

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

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


        return homework_rubrics;
    }

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

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

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

        await homework_rubrics.destroy({
            transaction
        });

        return homework_rubrics;
    }

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

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

        if (!homework_rubrics) {
            return homework_rubrics;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.rubric_scores_rubric_item = await homework_rubrics.getRubric_scores_rubric_item({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.homework = await homework_rubrics.getHomework({
            transaction
        });
        
        
        output.schools = await homework_rubrics.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.schools,
        as: 'schools',
        
      },



    ];

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

            
            if (filter.criterion_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'homework_rubrics',
                        'criterion_title',
                        filter.criterion_title,
                    ),
                };
            }
            
            if (filter.criterion_description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'homework_rubrics',
                        'criterion_description',
                        filter.criterion_description,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            


      

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

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

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

    
};

