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

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

        const gradebook_entries = await db.gradebook_entries.create(
            {
                id: data.id || undefined,
        
        score: data.score
        ||
        null
            ,
            
        entry_status: data.entry_status
        ||
        null
            ,
            
        recorded_at: data.recorded_at
        ||
        null
            ,
            
        remarks: data.remarks
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await gradebook_entries.setGradebook_column( data.gradebook_column || null, {
            transaction,
        });
        
        await gradebook_entries.setStudent( data.student || null, {
            transaction,
        });
        
        await gradebook_entries.setRecorded_by( data.recorded_by || null, {
            transaction,
        });
        
        await gradebook_entries.setSchools( data.schools || null, {
            transaction,
        });
        

        

        

        return gradebook_entries;
    }
    

    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_entriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                score: item.score
            ||
            null
            ,
            
                entry_status: item.entry_status
            ||
            null
            ,
            
                recorded_at: item.recorded_at
            ||
            null
            ,
            
                remarks: item.remarks
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return gradebook_entries;
    }

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


        

        const updatePayload = {};
        
        if (data.score !== undefined) updatePayload.score = data.score;
        
        
        if (data.entry_status !== undefined) updatePayload.entry_status = data.entry_status;
        
        
        if (data.recorded_at !== undefined) updatePayload.recorded_at = data.recorded_at;
        
        
        if (data.remarks !== undefined) updatePayload.remarks = data.remarks;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.gradebook_column !== undefined) {
            await gradebook_entries.setGradebook_column(
              
              data.gradebook_column,
              
              { transaction }
            );
        }
        
        if (data.student !== undefined) {
            await gradebook_entries.setStudent(
              
              data.student,
              
              { transaction }
            );
        }
        
        if (data.recorded_by !== undefined) {
            await gradebook_entries.setRecorded_by(
              
              data.recorded_by,
              
              { transaction }
            );
        }
        
        if (data.schools !== undefined) {
            await gradebook_entries.setSchools(
              
              data.schools,
              
              { transaction }
            );
        }
        

        
        

        

        return gradebook_entries;
    }

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

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

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


        return gradebook_entries;
    }

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

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

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

        await gradebook_entries.destroy({
            transaction
        });

        return gradebook_entries;
    }

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

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

        if (!gradebook_entries) {
            return gradebook_entries;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.gradebook_column = await gradebook_entries.getGradebook_column({
            transaction
        });
        
        
        output.student = await gradebook_entries.getStudent({
            transaction
        });
        
        
        output.recorded_by = await gradebook_entries.getRecorded_by({
            transaction
        });
        
        
        output.schools = await gradebook_entries.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.gradebook_columns,
        as: 'gradebook_column',
        
        where: filter.gradebook_column ? {
          [Op.or]: [
            { id: { [Op.in]: filter.gradebook_column.split('|').map(term => Utils.uuid(term)) } },
            {
              column_name: {
                [Op.or]: filter.gradebook_column.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.users,
        as: 'recorded_by',
        
        where: filter.recorded_by ? {
          [Op.or]: [
            { id: { [Op.in]: filter.recorded_by.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.recorded_by.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.remarks) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'gradebook_entries',
                        'remarks',
                        filter.remarks,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      

      

      

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

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

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

    
};

