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

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

        const class_sections = await db.class_sections.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        capacity: data.capacity
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await class_sections.setSchool_year( data.school_year || null, {
            transaction,
        });
        
        await class_sections.setGrade( data.grade || null, {
            transaction,
        });
        
        await class_sections.setStream( data.stream || null, {
            transaction,
        });
        
        await class_sections.setHomeroom_teacher( data.homeroom_teacher || null, {
            transaction,
        });
        

        

        

        return class_sections;
    }
    

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

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

        // For each item created, replace relation files
        

        return class_sections;
    }

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

        const class_sections = await db.class_sections.findByPk(id, {}, {transaction});


        

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

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

        
        
        if (data.school_year !== undefined) {
            await class_sections.setSchool_year(
              
              data.school_year,
              
              { transaction }
            );
        }
        
        if (data.grade !== undefined) {
            await class_sections.setGrade(
              
              data.grade,
              
              { transaction }
            );
        }
        
        if (data.stream !== undefined) {
            await class_sections.setStream(
              
              data.stream,
              
              { transaction }
            );
        }
        
        if (data.homeroom_teacher !== undefined) {
            await class_sections.setHomeroom_teacher(
              
              data.homeroom_teacher,
              
              { transaction }
            );
        }
        

        
        

        

        return class_sections;
    }

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

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

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


        return class_sections;
    }

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

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

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

        await class_sections.destroy({
            transaction
        });

        return class_sections;
    }

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

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

        if (!class_sections) {
            return class_sections;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.enrollments_class_section = await class_sections.getEnrollments_class_section({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.attendance_sessions_class_section = await class_sections.getAttendance_sessions_class_section({
            transaction
        });
        
        
        
        output.class_schedules_class_section = await class_sections.getClass_schedules_class_section({
            transaction
        });
        
        
        output.assignments_class_section = await class_sections.getAssignments_class_section({
            transaction
        });
        
        
        
        output.lesson_plans_class_section = await class_sections.getLesson_plans_class_section({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.school_year = await class_sections.getSchool_year({
            transaction
        });
        
        
        output.grade = await class_sections.getGrade({
            transaction
        });
        
        
        output.stream = await class_sections.getStream({
            transaction
        });
        
        
        output.homeroom_teacher = await class_sections.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.school_years,
        as: 'school_year',
        
        where: filter.school_year ? {
          [Op.or]: [
            { id: { [Op.in]: filter.school_year.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.school_year.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

      {
        model: db.staff_members,
        as: 'homeroom_teacher',
        
        where: filter.homeroom_teacher ? {
          [Op.or]: [
            { id: { [Op.in]: filter.homeroom_teacher.split('|').map(term => Utils.uuid(term)) } },
            {
              full_name: {
                [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(
                        'class_sections',
                        'name',
                        filter.name,
                    ),
                };
            }
            

            
            

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

        const records = await db.class_sections.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,
        }));
    }

    
};

