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

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

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

        
        await staff.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await staff.setCampus( data.campus || null, {
            transaction,
        });
        
        await staff.setUser( data.user || null, {
            transaction,
        });
        

        

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

        return staff;
    }
    

    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 staffData = data.map((item, index) => ({
                id: item.id || undefined,
                
                employee_number: item.employee_number
            ||
            null
            ,
            
                job_title: item.job_title
            ||
            null
            ,
            
                staff_type: item.staff_type
            ||
            null
            ,
            
                hire_date: item.hire_date
            ||
            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 staff = await db.staff.bulkCreate(staffData, { transaction });

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

        return staff;
    }

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

        const staff = await db.staff.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.staff_type !== undefined) updatePayload.staff_type = data.staff_type;
        
        
        if (data.hire_date !== undefined) updatePayload.hire_date = data.hire_date;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await staff.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.campus !== undefined) {
            await staff.setCampus(
              
              data.campus,
              
              { transaction }
            );
        }
        
        if (data.user !== undefined) {
            await staff.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

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

        return staff;
    }

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

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

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


        return staff;
    }

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

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

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

        await staff.destroy({
            transaction
        });

        return staff;
    }

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

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

        if (!staff) {
            return staff;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.classes_homeroom_teacher = await staff.getClasses_homeroom_teacher({
            transaction
        });
        
        
        
        output.class_subjects_teacher = await staff.getClass_subjects_teacher({
            transaction
        });
        
        
        
        
        output.attendance_sessions_taken_by = await staff.getAttendance_sessions_taken_by({
            transaction
        });
        
        
        
        
        
        output.payments_received_by = await staff.getPayments_received_by({
            transaction
        });
        
        
        
        
        
        
        
        
        output.organization = await staff.getOrganization({
            transaction
        });
        
        
        output.campus = await staff.getCampus({
            transaction
        });
        
        
        output.user = await staff.getUser({
            transaction
        });
        
        
        output.photo = await staff.getPhoto({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.organizations,
        as: 'organization',
        
      },

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

      {
        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.file,
        as: 'photo',
      },

    ];

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

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

            
            

            
            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.staff_type) {
                where = {
                    ...where,
                staff_type: filter.staff_type,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      
      if (filter.organization) {
        const listItems = filter.organization.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationId: {[Op.or]: listItems}
        };
      }
      

      

      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'staff',
                        'employee_number',
                        query,
                    ),
                ],
            };
        }

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

    
};

