
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
            ,
            
        code: data.code
        ||
        null
            ,
            
        capacity: data.capacity
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await classes.setSchool( data.school || null, {
            transaction,
        });
        
        await classes.setCampus( data.campus || null, {
            transaction,
        });
        
        await classes.setAcademic_year( data.academic_year || null, {
            transaction,
        });
        
        await classes.setGrade_level( data.grade_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
            ,
            
                code: item.code
            ||
            null
            ,
            
                capacity: item.capacity
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            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 classes = await db.classes.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.code !== undefined) updatePayload.code = data.code;
        
        
        if (data.capacity !== undefined) updatePayload.capacity = data.capacity;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.school !== undefined) {
            await classes.setSchool(
              
              data.school,
              
              { transaction }
            );
        }
        
        if (data.campus !== undefined) {
            await classes.setCampus(
              
              data.campus,
              
              { transaction }
            );
        }
        
        if (data.academic_year !== undefined) {
            await classes.setAcademic_year(
              
              data.academic_year,
              
              { transaction }
            );
        }
        
        if (data.grade_level !== undefined) {
            await classes.setGrade_level(
              
              data.grade_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.class_enrollments_class = await classes.getClass_enrollments_class({
            transaction
        });
        
        
        output.course_sections_class = await classes.getCourse_sections_class({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.school = await classes.getSchool({
            transaction
        });
        
        
        output.campus = await classes.getCampus({
            transaction
        });
        
        
        output.academic_year = await classes.getAcademic_year({
            transaction
        });
        
        
        output.grade_level = await classes.getGrade_level({
            transaction
        });
        
        
        output.homeroom_teacher = await classes.getHomeroom_teacher({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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

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

      {
        model: db.teachers,
        as: 'homeroom_teacher',
        
        where: filter.homeroom_teacher ? {
          [Op.or]: [
            { id: { [Op.in]: filter.homeroom_teacher.split('|').map(term => Utils.uuid(term)) } },
            {
              employee_number: {
                [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.code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'classes',
                        'code',
                        filter.code,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

      

      

      

      



            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,
                        },
                    };
                }
            }
        }
        

        

        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, ) {
        let where = {};
        
        

        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,
        }));
    }

    
};

