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

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

        const employees = await db.employees.create(
            {
                id: data.id || undefined,
        
        employee_number: data.employee_number
        ||
        null
            ,
            
        job_title: data.job_title
        ||
        null
            ,
            
        hire_date: data.hire_date
        ||
        null
            ,
            
        employment_status: data.employment_status
        ||
        null
            ,
            
        base_salary: data.base_salary
        ||
        null
            ,
            
        commission_eligible: data.commission_eligible
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await employees.setUser( data.user || null, {
            transaction,
        });
        
        await employees.setBranch( data.branch || null, {
            transaction,
        });
        
        await employees.setDepartment( data.department || null, {
            transaction,
        });
        
        await employees.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return employees;
    }
    

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

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

        // For each item created, replace relation files
        

        return employees;
    }

    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 employees = await db.employees.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.hire_date !== undefined) updatePayload.hire_date = data.hire_date;
        
        
        if (data.employment_status !== undefined) updatePayload.employment_status = data.employment_status;
        
        
        if (data.base_salary !== undefined) updatePayload.base_salary = data.base_salary;
        
        
        if (data.commission_eligible !== undefined) updatePayload.commission_eligible = data.commission_eligible;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await employees.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.branch !== undefined) {
            await employees.setBranch(
              
              data.branch,
              
              { transaction }
            );
        }
        
        if (data.department !== undefined) {
            await employees.setDepartment(
              
              data.department,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await employees.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return employees;
    }

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

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

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


        return employees;
    }

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

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

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

        await employees.destroy({
            transaction
        });

        return employees;
    }

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

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

        if (!employees) {
            return employees;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.shift_assignments_employee = await employees.getShift_assignments_employee({
            transaction
        });
        
        
        output.attendance_records_employee = await employees.getAttendance_records_employee({
            transaction
        });
        
        
        
        output.payroll_items_employee = await employees.getPayroll_items_employee({
            transaction
        });
        
        
        output.performance_reviews_employee = await employees.getPerformance_reviews_employee({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.user = await employees.getUser({
            transaction
        });
        
        
        output.branch = await employees.getBranch({
            transaction
        });
        
        
        output.department = await employees.getDepartment({
            transaction
        });
        
        
        output.organizations = await employees.getOrganizations({
            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.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.branches,
        as: 'branch',
        
        where: filter.branch ? {
          [Op.or]: [
            { id: { [Op.in]: filter.branch.split('|').map(term => Utils.uuid(term)) } },
            {
              branch_name: {
                [Op.or]: filter.branch.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.departments,
        as: 'department',
        
        where: filter.department ? {
          [Op.or]: [
            { id: { [Op.in]: filter.department.split('|').map(term => Utils.uuid(term)) } },
            {
              department_name: {
                [Op.or]: filter.department.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            

            
            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.base_salaryRange) {
                const [start, end] = filter.base_salaryRange;

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

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

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

            
            if (filter.job_title) {
                where = {
                    ...where,
                job_title: filter.job_title,
            };
            }
            
            if (filter.employment_status) {
                where = {
                    ...where,
                employment_status: filter.employment_status,
            };
            }
            
            if (filter.commission_eligible) {
                where = {
                    ...where,
                commission_eligible: filter.commission_eligible,
            };
            }
            


      

      

      

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

        where = {
          ...where,
          organizationsId: {[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.employees.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(
                        'employees',
                        'employee_number',
                        query,
                    ),
                ],
            };
        }

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

    
};

