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

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

        const gradebooks = await db.gradebooks.create(
            {
                id: data.id || undefined,
        
        gradebook_name: data.gradebook_name
        ||
        null
            ,
            
        term: data.term
        ||
        null
            ,
            
        start_at: data.start_at
        ||
        null
            ,
            
        end_at: data.end_at
        ||
        null
            ,
            
        is_published: data.is_published
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await gradebooks.setSchool( data.school || null, {
            transaction,
        });
        
        await gradebooks.setClassroom( data.classroom || null, {
            transaction,
        });
        
        await gradebooks.setSubject( data.subject || null, {
            transaction,
        });
        
        await gradebooks.setOwner_teacher( data.owner_teacher || null, {
            transaction,
        });
        

        

        

        return gradebooks;
    }
    

    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 gradebooksData = data.map((item, index) => ({
                id: item.id || undefined,
                
                gradebook_name: item.gradebook_name
            ||
            null
            ,
            
                term: item.term
            ||
            null
            ,
            
                start_at: item.start_at
            ||
            null
            ,
            
                end_at: item.end_at
            ||
            null
            ,
            
                is_published: item.is_published
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return gradebooks;
    }

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


        

        const updatePayload = {};
        
        if (data.gradebook_name !== undefined) updatePayload.gradebook_name = data.gradebook_name;
        
        
        if (data.term !== undefined) updatePayload.term = data.term;
        
        
        if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
        
        
        if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
        
        
        if (data.is_published !== undefined) updatePayload.is_published = data.is_published;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.school !== undefined) {
            await gradebooks.setSchool(
              
              data.school,
              
              { transaction }
            );
        }
        
        if (data.classroom !== undefined) {
            await gradebooks.setClassroom(
              
              data.classroom,
              
              { transaction }
            );
        }
        
        if (data.subject !== undefined) {
            await gradebooks.setSubject(
              
              data.subject,
              
              { transaction }
            );
        }
        
        if (data.owner_teacher !== undefined) {
            await gradebooks.setOwner_teacher(
              
              data.owner_teacher,
              
              { transaction }
            );
        }
        

        
        

        

        return gradebooks;
    }

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

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

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


        return gradebooks;
    }

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

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

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

        await gradebooks.destroy({
            transaction
        });

        return gradebooks;
    }

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

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

        if (!gradebooks) {
            return gradebooks;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.gradebook_columns_gradebook = await gradebooks.getGradebook_columns_gradebook({
            transaction
        });
        
        
        
        output.adviser_reports_gradebook = await gradebooks.getAdviser_reports_gradebook({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.school = await gradebooks.getSchool({
            transaction
        });
        
        
        output.classroom = await gradebooks.getClassroom({
            transaction
        });
        
        
        output.subject = await gradebooks.getSubject({
            transaction
        });
        
        
        output.owner_teacher = await gradebooks.getOwner_teacher({
            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.schools,
        as: 'school',
        
      },

      {
        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: 'owner_teacher',
        
        where: filter.owner_teacher ? {
          [Op.or]: [
            { id: { [Op.in]: filter.owner_teacher.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.owner_teacher.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

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

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

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

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

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

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

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

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


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

        where = {
          ...where,
          schoolId: {[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.gradebooks.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(
                        'gradebooks',
                        'gradebook_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

