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

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

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

        
        await classes.setSchool( data.school || null, {
            transaction,
        });
        
        await classes.setAcademic_year( data.academic_year || null, {
            transaction,
        });
        
        await classes.setEducation_level( data.education_level || null, {
            transaction,
        });
        
        await classes.setHomeroom_teacher( data.homeroom_teacher || null, {
            transaction,
        });
        

        

        

        return classes;
    }
    

    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 classesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                grade: item.grade
            ||
            null
            ,
            
                homeroom_label: item.homeroom_label
            ||
            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 classes = await db.classes.bulkCreate(classesData, { transaction });

        // For each item created, replace relation files
        

        return classes;
    }

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


        

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

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

        
        
        if (data.school !== undefined) {
            await classes.setSchool(
              
              data.school,
              
              { transaction }
            );
        }
        
        if (data.academic_year !== undefined) {
            await classes.setAcademic_year(
              
              data.academic_year,
              
              { transaction }
            );
        }
        
        if (data.education_level !== undefined) {
            await classes.setEducation_level(
              
              data.education_level,
              
              { transaction }
            );
        }
        
        if (data.homeroom_teacher !== undefined) {
            await classes.setHomeroom_teacher(
              
              data.homeroom_teacher,
              
              { transaction }
            );
        }
        

        
        

        

        return classes;
    }

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

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

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


        return classes;
    }

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

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

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

        await classes.destroy({
            transaction
        });

        return classes;
    }

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

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

        if (!classes) {
            return classes;
        }

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

        
        
        
        
        
        
        
        
        output.students_current_class = await classes.getStudents_current_class({
            transaction
        });
        
        
        
        
        output.class_subjects_class = await classes.getClass_subjects_class({
            transaction
        });
        
        
        output.timetable_entries_class = await classes.getTimetable_entries_class({
            transaction
        });
        
        
        output.attendance_sessions_class = await classes.getAttendance_sessions_class({
            transaction
        });
        
        
        
        output.announcements_target_class = await classes.getAnnouncements_target_class({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.fee_definitions_class = await classes.getFee_definitions_class({
            transaction
        });
        
        
        
        
        
        
        output.school = await classes.getSchool({
            transaction
        });
        
        
        output.academic_year = await classes.getAcademic_year({
            transaction
        });
        
        
        output.education_level = await classes.getEducation_level({
            transaction
        });
        
        
        output.homeroom_teacher = await classes.getHomeroom_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.academic_years,
        as: 'academic_year',
        
        where: filter.academic_year ? {
          [Op.or]: [
            { id: { [Op.in]: filter.academic_year.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.academic_year.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.education_levels,
        as: 'education_level',
        
        where: filter.education_level ? {
          [Op.or]: [
            { id: { [Op.in]: filter.education_level.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.education_level.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'homeroom_teacher',
        
        where: filter.homeroom_teacher ? {
          [Op.or]: [
            { id: { [Op.in]: filter.homeroom_teacher.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.homeroom_teacher.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'classes',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.homeroom_label) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'classes',
                        'homeroom_label',
                        filter.homeroom_label,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    grade: {
                    ...where.grade,
                            [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.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.classes.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(
                        'classes',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

