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

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

        const grades = await db.grades.create(
            {
                id: data.id || undefined,
        
        grade_number: data.grade_number
        ||
        null
            ,
            
        level: data.level
        ||
        null
            ,
            
        label: data.label
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return grades;
    }
    

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

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

        // For each item created, replace relation files
        

        return grades;
    }

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

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


        

        const updatePayload = {};
        
        if (data.grade_number !== undefined) updatePayload.grade_number = data.grade_number;
        
        
        if (data.level !== undefined) updatePayload.level = data.level;
        
        
        if (data.label !== undefined) updatePayload.label = data.label;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return grades;
    }

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

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

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


        return grades;
    }

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

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

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

        await grades.destroy({
            transaction
        });

        return grades;
    }

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

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

        if (!grades) {
            return grades;
        }

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

        
        
        
        
        
        
        
        
        
        
        output.subject_offerings_grade = await grades.getSubject_offerings_grade({
            transaction
        });
        
        
        
        output.students_current_grade = await grades.getStudents_current_grade({
            transaction
        });
        
        
        output.class_sections_grade = await grades.getClass_sections_grade({
            transaction
        });
        
        
        
        
        
        
        
        
        output.study_materials_grade = await grades.getStudy_materials_grade({
            transaction
        });
        
        
        output.exams_grade = await grades.getExams_grade({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.admission_applications_requested_grade = await grades.getAdmission_applications_requested_grade({
            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 = [



    ];

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

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

            
            

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

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

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

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

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




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

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

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

    
};

