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

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

        const teachers = await db.teachers.create(
            {
                id: data.id || undefined,
        
        employee_number: data.employee_number
        ||
        null
            ,
            
        job_title: data.job_title
        ||
        null
            ,
            
        employment_type: data.employment_type
        ||
        null
            ,
            
        hire_date: data.hire_date
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        bio: data.bio
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await teachers.setUser( data.user || null, {
            transaction,
        });
        
        await teachers.setSchool( data.school || null, {
            transaction,
        });
        
        await teachers.setCampus( data.campus || null, {
            transaction,
        });
        

        

        

        return teachers;
    }
    

    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 teachersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                employee_number: item.employee_number
            ||
            null
            ,
            
                job_title: item.job_title
            ||
            null
            ,
            
                employment_type: item.employment_type
            ||
            null
            ,
            
                hire_date: item.hire_date
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                bio: item.bio
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return teachers;
    }

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

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


        

        const updatePayload = {};
        
        if (data.employee_number !== undefined) updatePayload.employee_number = data.employee_number;
        
        
        if (data.job_title !== undefined) updatePayload.job_title = data.job_title;
        
        
        if (data.employment_type !== undefined) updatePayload.employment_type = data.employment_type;
        
        
        if (data.hire_date !== undefined) updatePayload.hire_date = data.hire_date;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.bio !== undefined) updatePayload.bio = data.bio;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await teachers.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.school !== undefined) {
            await teachers.setSchool(
              
              data.school,
              
              { transaction }
            );
        }
        
        if (data.campus !== undefined) {
            await teachers.setCampus(
              
              data.campus,
              
              { transaction }
            );
        }
        

        
        

        

        return teachers;
    }

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

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

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


        return teachers;
    }

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

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

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

        await teachers.destroy({
            transaction
        });

        return teachers;
    }

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

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

        if (!teachers) {
            return teachers;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.classes_homeroom_teacher = await teachers.getClasses_homeroom_teacher({
            transaction
        });
        
        
        
        output.course_sections_teacher = await teachers.getCourse_sections_teacher({
            transaction
        });
        
        
        
        output.attendance_sessions_teacher = await teachers.getAttendance_sessions_teacher({
            transaction
        });
        
        
        
        output.assignments_teacher = await teachers.getAssignments_teacher({
            transaction
        });
        
        
        
        output.grade_items_teacher = await teachers.getGrade_items_teacher({
            transaction
        });
        
        
        
        
        
        
        
        
        output.user = await teachers.getUser({
            transaction
        });
        
        
        output.school = await teachers.getSchool({
            transaction
        });
        
        
        output.campus = await teachers.getCampus({
            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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.employee_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'teachers',
                        'employee_number',
                        filter.employee_number,
                    ),
                };
            }
            
            if (filter.job_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'teachers',
                        'job_title',
                        filter.job_title,
                    ),
                };
            }
            
            if (filter.bio) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'teachers',
                        'bio',
                        filter.bio,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.employment_type) {
                where = {
                    ...where,
                employment_type: filter.employment_type,
            };
            }
            
            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.teachers.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(
                        'teachers',
                        'employee_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

