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

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

        const course_sections = await db.course_sections.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        section_code: data.section_code
        ||
        null
            ,
            
        grading_scheme: data.grading_scheme
        ||
        null
            ,
            
        pass_mark: data.pass_mark
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await course_sections.setClass( data.class || null, {
            transaction,
        });
        
        await course_sections.setSubject( data.subject || null, {
            transaction,
        });
        
        await course_sections.setTerm( data.term || null, {
            transaction,
        });
        
        await course_sections.setTeacher( data.teacher || null, {
            transaction,
        });
        

        

        

        return course_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 course_sectionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                section_code: item.section_code
            ||
            null
            ,
            
                grading_scheme: item.grading_scheme
            ||
            null
            ,
            
                pass_mark: item.pass_mark
            ||
            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 course_sections = await db.course_sections.bulkCreate(course_sectionsData, { transaction });

        // For each item created, replace relation files
        

        return course_sections;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.section_code !== undefined) updatePayload.section_code = data.section_code;
        
        
        if (data.grading_scheme !== undefined) updatePayload.grading_scheme = data.grading_scheme;
        
        
        if (data.pass_mark !== undefined) updatePayload.pass_mark = data.pass_mark;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.class !== undefined) {
            await course_sections.setClass(
              
              data.class,
              
              { transaction }
            );
        }
        
        if (data.subject !== undefined) {
            await course_sections.setSubject(
              
              data.subject,
              
              { transaction }
            );
        }
        
        if (data.term !== undefined) {
            await course_sections.setTerm(
              
              data.term,
              
              { transaction }
            );
        }
        
        if (data.teacher !== undefined) {
            await course_sections.setTeacher(
              
              data.teacher,
              
              { transaction }
            );
        }
        

        
        

        

        return course_sections;
    }

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

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

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


        return course_sections;
    }

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

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

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

        await course_sections.destroy({
            transaction
        });

        return course_sections;
    }

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

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

        if (!course_sections) {
            return course_sections;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.timetable_entries_course_section = await course_sections.getTimetable_entries_course_section({
            transaction
        });
        
        
        output.attendance_sessions_course_section = await course_sections.getAttendance_sessions_course_section({
            transaction
        });
        
        
        
        output.assignments_course_section = await course_sections.getAssignments_course_section({
            transaction
        });
        
        
        
        output.grade_items_course_section = await course_sections.getGrade_items_course_section({
            transaction
        });
        
        
        
        
        
        
        
        
        output.class = await course_sections.getClass({
            transaction
        });
        
        
        output.subject = await course_sections.getSubject({
            transaction
        });
        
        
        output.term = await course_sections.getTerm({
            transaction
        });
        
        
        output.teacher = await course_sections.getTeacher({
            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.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.terms,
        as: 'term',
        
        where: filter.term ? {
          [Op.or]: [
            { id: { [Op.in]: filter.term.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.term.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

            
            

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

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

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

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

            
            if (filter.grading_scheme) {
                where = {
                    ...where,
                grading_scheme: filter.grading_scheme,
            };
            }
            
            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.course_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(
                        'course_sections',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

    
};

