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

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

        const gradebook_columns = await db.gradebook_columns.create(
            {
                id: data.id || undefined,
        
        column_name: data.column_name
        ||
        null
            ,
            
        column_type: data.column_type
        ||
        null
            ,
            
        max_score: data.max_score
        ||
        null
            ,
            
        weight: data.weight
        ||
        null
            ,
            
        sort_order: data.sort_order
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return gradebook_columns;
    }
    

    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 gradebook_columnsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                column_name: item.column_name
            ||
            null
            ,
            
                column_type: item.column_type
            ||
            null
            ,
            
                max_score: item.max_score
            ||
            null
            ,
            
                weight: item.weight
            ||
            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 gradebook_columns = await db.gradebook_columns.bulkCreate(gradebook_columnsData, { transaction });

        // For each item created, replace relation files
        

        return gradebook_columns;
    }

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


        

        const updatePayload = {};
        
        if (data.column_name !== undefined) updatePayload.column_name = data.column_name;
        
        
        if (data.column_type !== undefined) updatePayload.column_type = data.column_type;
        
        
        if (data.max_score !== undefined) updatePayload.max_score = data.max_score;
        
        
        if (data.weight !== undefined) updatePayload.weight = data.weight;
        
        
        if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return gradebook_columns;
    }

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

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

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


        return gradebook_columns;
    }

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

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

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

        await gradebook_columns.destroy({
            transaction
        });

        return gradebook_columns;
    }

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

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

        if (!gradebook_columns) {
            return gradebook_columns;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.gradebook_entries_gradebook_column = await gradebook_columns.getGradebook_entries_gradebook_column({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.gradebook = await gradebook_columns.getGradebook({
            transaction
        });
        
        
        output.homework = await gradebook_columns.getHomework({
            transaction
        });
        
        
        output.schools = await gradebook_columns.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.gradebooks,
        as: 'gradebook',
        
        where: filter.gradebook ? {
          [Op.or]: [
            { id: { [Op.in]: filter.gradebook.split('|').map(term => Utils.uuid(term)) } },
            {
              gradebook_name: {
                [Op.or]: filter.gradebook.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        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.column_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'gradebook_columns',
                        'column_name',
                        filter.column_name,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    weight: {
                    ...where.weight,
                            [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.column_type) {
                where = {
                    ...where,
                column_type: filter.column_type,
            };
            }
            


      

      

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

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

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

    
};

