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

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

        const staff_members = await db.staff_members.create(
            {
                id: data.id || undefined,
        
        full_name: data.full_name
        ||
        null
            ,
            
        staff_role: data.staff_role
        ||
        null
            ,
            
        bio: data.bio
        ||
        null
            ,
            
        phone_number: data.phone_number
        ||
        null
            ,
            
        email: data.email
        ||
        null
            ,
            
        public_profile: data.public_profile
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await staff_members.setUser( data.user || null, {
            transaction,
        });
        

        
        await staff_members.setSubjects_taught(data.subjects_taught || [], {
            transaction,
        });
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.staff_members.getTableName(),
                belongsToColumn: 'photo',
                belongsToId: staff_members.id,
            },
            data.photo,
            options,
        );
        

        return staff_members;
    }
    

    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 staff_membersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                full_name: item.full_name
            ||
            null
            ,
            
                staff_role: item.staff_role
            ||
            null
            ,
            
                bio: item.bio
            ||
            null
            ,
            
                phone_number: item.phone_number
            ||
            null
            ,
            
                email: item.email
            ||
            null
            ,
            
                public_profile: item.public_profile
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < staff_members.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.staff_members.getTableName(),
                    belongsToColumn: 'photo',
                    belongsToId: staff_members[i].id,
                },
                data[i].photo,
                options,
            );
        }
        

        return staff_members;
    }

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

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


        

        const updatePayload = {};
        
        if (data.full_name !== undefined) updatePayload.full_name = data.full_name;
        
        
        if (data.staff_role !== undefined) updatePayload.staff_role = data.staff_role;
        
        
        if (data.bio !== undefined) updatePayload.bio = data.bio;
        
        
        if (data.phone_number !== undefined) updatePayload.phone_number = data.phone_number;
        
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.public_profile !== undefined) updatePayload.public_profile = data.public_profile;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await staff_members.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        
        if (data.subjects_taught !== undefined) {
            await staff_members.setSubjects_taught(data.subjects_taught, { transaction });
        }
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.staff_members.getTableName(),
                belongsToColumn: 'photo',
                belongsToId: staff_members.id,
            },
            data.photo,
            options,
        );
        

        return staff_members;
    }

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

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

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


        return staff_members;
    }

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

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

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

        await staff_members.destroy({
            transaction
        });

        return staff_members;
    }

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

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

        if (!staff_members) {
            return staff_members;
        }

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

        
        
        
        
        
        
        
        
        
        
        output.subject_offerings_responsible_teacher = await staff_members.getSubject_offerings_responsible_teacher({
            transaction
        });
        
        
        
        
        output.class_sections_homeroom_teacher = await staff_members.getClass_sections_homeroom_teacher({
            transaction
        });
        
        
        
        
        
        
        output.news_posts_author = await staff_members.getNews_posts_author({
            transaction
        });
        
        
        
        output.study_materials_uploaded_by = await staff_members.getStudy_materials_uploaded_by({
            transaction
        });
        
        
        
        output.exam_results_entered_by = await staff_members.getExam_results_entered_by({
            transaction
        });
        
        
        output.attendance_sessions_teacher = await staff_members.getAttendance_sessions_teacher({
            transaction
        });
        
        
        
        output.class_schedules_teacher = await staff_members.getClass_schedules_teacher({
            transaction
        });
        
        
        output.assignments_teacher = await staff_members.getAssignments_teacher({
            transaction
        });
        
        
        
        output.lesson_plans_teacher = await staff_members.getLesson_plans_teacher({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.user = await staff_members.getUser({
            transaction
        });
        
        
        output.photo = await staff_members.getPhoto({
            transaction
        });
        
        
        output.subjects_taught = await staff_members.getSubjects_taught({
            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.subjects,
        as: 'subjects_taught',
        required: false,
      },


      {
        model: db.file,
        as: 'photo',
      },

    ];

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

            
            if (filter.full_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'staff_members',
                        'full_name',
                        filter.full_name,
                    ),
                };
            }
            
            if (filter.bio) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'staff_members',
                        'bio',
                        filter.bio,
                    ),
                };
            }
            
            if (filter.phone_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'staff_members',
                        'phone_number',
                        filter.phone_number,
                    ),
                };
            }
            
            if (filter.email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'staff_members',
                        'email',
                        filter.email,
                    ),
                };
            }
            

            
            

            

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

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


      


      if (filter.subjects_taught) {
        const searchTerms = filter.subjects_taught.split('|');

        include = [
          {
            model: db.subjects,
            as: 'subjects_taught_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name_en: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

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

    
};

