
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
            ,
            
        first_name: data.first_name
        ||
        null
            ,
            
        last_name: data.last_name
        ||
        null
            ,
            
        preferred_name: data.preferred_name
        ||
        null
            ,
            
        email: data.email
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        national_id: data.national_id
        ||
        null
            ,
            
        date_of_birth: data.date_of_birth
        ||
        null
            ,
            
        gender: data.gender
        ||
        null
            ,
            
        address: data.address
        ||
        null
            ,
            
        hire_date: data.hire_date
        ||
        null
            ,
            
        termination_date: data.termination_date
        ||
        null
            ,
            
        employment_status: data.employment_status
        ||
        null
            ,
            
        employment_type: data.employment_type
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await employees.setCompany( data.company || null, {
            transaction,
        });
        
        await employees.setDepartment( data.department || null, {
            transaction,
        });
        
        await employees.setJob_title( data.job_title || null, {
            transaction,
        });
        
        await employees.setWork_location( data.work_location || null, {
            transaction,
        });
        
        await employees.setManager( data.manager || null, {
            transaction,
        });
        
        await employees.setUser_account( data.user_account || null, {
            transaction,
        });
        
        await employees.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        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
            ,
            
                first_name: item.first_name
            ||
            null
            ,
            
                last_name: item.last_name
            ||
            null
            ,
            
                preferred_name: item.preferred_name
            ||
            null
            ,
            
                email: item.email
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                national_id: item.national_id
            ||
            null
            ,
            
                date_of_birth: item.date_of_birth
            ||
            null
            ,
            
                gender: item.gender
            ||
            null
            ,
            
                address: item.address
            ||
            null
            ,
            
                hire_date: item.hire_date
            ||
            null
            ,
            
                termination_date: item.termination_date
            ||
            null
            ,
            
                employment_status: item.employment_status
            ||
            null
            ,
            
                employment_type: item.employment_type
            ||
            null
            ,
            
            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
        
        for (let i = 0; i < employees.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.employees.getTableName(),
                    belongsToColumn: 'profile_photo',
                    belongsToId: employees[i].id,
                },
                data[i].profile_photo,
                options,
            );
        }
        

        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.first_name !== undefined) updatePayload.first_name = data.first_name;
        
        
        if (data.last_name !== undefined) updatePayload.last_name = data.last_name;
        
        
        if (data.preferred_name !== undefined) updatePayload.preferred_name = data.preferred_name;
        
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.phone !== undefined) updatePayload.phone = data.phone;
        
        
        if (data.national_id !== undefined) updatePayload.national_id = data.national_id;
        
        
        if (data.date_of_birth !== undefined) updatePayload.date_of_birth = data.date_of_birth;
        
        
        if (data.gender !== undefined) updatePayload.gender = data.gender;
        
        
        if (data.address !== undefined) updatePayload.address = data.address;
        
        
        if (data.hire_date !== undefined) updatePayload.hire_date = data.hire_date;
        
        
        if (data.termination_date !== undefined) updatePayload.termination_date = data.termination_date;
        
        
        if (data.employment_status !== undefined) updatePayload.employment_status = data.employment_status;
        
        
        if (data.employment_type !== undefined) updatePayload.employment_type = data.employment_type;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await employees.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.department !== undefined) {
            await employees.setDepartment(
              
              data.department,
              
              { transaction }
            );
        }
        
        if (data.job_title !== undefined) {
            await employees.setJob_title(
              
              data.job_title,
              
              { transaction }
            );
        }
        
        if (data.work_location !== undefined) {
            await employees.setWork_location(
              
              data.work_location,
              
              { transaction }
            );
        }
        
        if (data.manager !== undefined) {
            await employees.setManager(
              
              data.manager,
              
              { transaction }
            );
        }
        
        if (data.user_account !== undefined) {
            await employees.setUser_account(
              
              data.user_account,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await employees.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        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.employment_contracts_employee = await employees.getEmployment_contracts_employee({
            transaction
        });
        
        
        
        output.leave_requests_employee = await employees.getLeave_requests_employee({
            transaction
        });
        
        output.leave_requests_approver = await employees.getLeave_requests_approver({
            transaction
        });
        
        
        
        
        output.employee_schedule_assignments_employee = await employees.getEmployee_schedule_assignments_employee({
            transaction
        });
        
        
        output.time_entries_employee = await employees.getTime_entries_employee({
            transaction
        });
        
        output.time_entries_approved_by = await employees.getTime_entries_approved_by({
            transaction
        });
        
        
        
        
        output.expense_claims_employee = await employees.getExpense_claims_employee({
            transaction
        });
        
        output.expense_claims_approver = await employees.getExpense_claims_approver({
            transaction
        });
        
        
        output.documents_employee = await employees.getDocuments_employee({
            transaction
        });
        
        
        
        
        
        
        output.company = await employees.getCompany({
            transaction
        });
        
        
        output.department = await employees.getDepartment({
            transaction
        });
        
        
        output.job_title = await employees.getJob_title({
            transaction
        });
        
        
        output.work_location = await employees.getWork_location({
            transaction
        });
        
        
        output.manager = await employees.getManager({
            transaction
        });
        
        
        output.user_account = await employees.getUser_account({
            transaction
        });
        
        
        output.profile_photo = await employees.getProfile_photo({
            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.companies,
        as: 'company',
        
        where: filter.company ? {
          [Op.or]: [
            { id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.company.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)) } },
            {
              name: {
                [Op.or]: filter.department.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

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

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



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

    ];

        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.first_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'first_name',
                        filter.first_name,
                    ),
                };
            }
            
            if (filter.last_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'last_name',
                        filter.last_name,
                    ),
                };
            }
            
            if (filter.preferred_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'preferred_name',
                        filter.preferred_name,
                    ),
                };
            }
            
            if (filter.email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'email',
                        filter.email,
                    ),
                };
            }
            
            if (filter.phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'phone',
                        filter.phone,
                    ),
                };
            }
            
            if (filter.national_id) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'national_id',
                        filter.national_id,
                    ),
                };
            }
            
            if (filter.address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'address',
                        filter.address,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    date_of_birth: {
                    ...where.date_of_birth,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.termination_dateRange) {
                const [start, end] = filter.termination_dateRange;

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

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

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

            
            if (filter.gender) {
                where = {
                    ...where,
                gender: filter.gender,
            };
            }
            
            if (filter.employment_status) {
                where = {
                    ...where,
                employment_status: filter.employment_status,
            };
            }
            
            if (filter.employment_type) {
                where = {
                    ...where,
                employment_type: filter.employment_type,
            };
            }
            


      

      

      

      

      

      

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

    
};

