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

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

        const class_subjects = await db.class_subjects.create(
            {
                id: data.id || undefined,
        
        weekly_sessions: data.weekly_sessions
        ||
        null
            ,
            
        active: data.active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await class_subjects.setClass( data.class || null, {
            transaction,
        });
        
        await class_subjects.setSubject( data.subject || null, {
            transaction,
        });
        
        await class_subjects.setTeacher( data.teacher || null, {
            transaction,
        });
        
        await class_subjects.setSchools( data.schools || null, {
            transaction,
        });
        

        

        

        return class_subjects;
    }
    

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

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

        // For each item created, replace relation files
        

        return class_subjects;
    }

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


        

        const updatePayload = {};
        
        if (data.weekly_sessions !== undefined) updatePayload.weekly_sessions = data.weekly_sessions;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.class !== undefined) {
            await class_subjects.setClass(
              
              data.class,
              
              { transaction }
            );
        }
        
        if (data.subject !== undefined) {
            await class_subjects.setSubject(
              
              data.subject,
              
              { transaction }
            );
        }
        
        if (data.teacher !== undefined) {
            await class_subjects.setTeacher(
              
              data.teacher,
              
              { transaction }
            );
        }
        
        if (data.schools !== undefined) {
            await class_subjects.setSchools(
              
              data.schools,
              
              { transaction }
            );
        }
        

        
        

        

        return class_subjects;
    }

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

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

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


        return class_subjects;
    }

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

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

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

        await class_subjects.destroy({
            transaction
        });

        return class_subjects;
    }

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

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

        if (!class_subjects) {
            return class_subjects;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.timetable_entries_class_subject = await class_subjects.getTimetable_entries_class_subject({
            transaction
        });
        
        
        
        
        
        output.assignments_class_subject = await class_subjects.getAssignments_class_subject({
            transaction
        });
        
        
        
        
        output.exams_class_subject = await class_subjects.getExams_class_subject({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.class = await class_subjects.getClass({
            transaction
        });
        
        
        output.subject = await class_subjects.getSubject({
            transaction
        });
        
        
        output.teacher = await class_subjects.getTeacher({
            transaction
        });
        
        
        output.schools = await class_subjects.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.classes,
        as: 'class',
        
        where: filter.class ? {
          [Op.or]: [
            { id: { [Op.in]: filter.class.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.class.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)) } },
            {
              name: {
                [Op.or]: filter.subject.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'teacher',
        
        where: filter.teacher ? {
          [Op.or]: [
            { id: { [Op.in]: filter.teacher.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.teacher.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.weekly_sessionsRange) {
                const [start, end] = filter.weekly_sessionsRange;

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

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

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

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


      

      

      

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

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

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

    
};

