
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const { isRestrictedPayrollUser } = require('../../security/payrollAccess');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Employee_pay_typesDBApi {
    

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

        const employee_pay_types = await db.employee_pay_types.create(
            {
                id: data.id || undefined,
        
        active: data.active
        ||
        false
        
            ,
            
        effective_start: data.effective_start
        ||
        null
            ,
            
        effective_end: data.effective_end
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await employee_pay_types.setEmployee( data.employee || null, {
            transaction,
        });
        
        await employee_pay_types.setPay_type( data.pay_type || null, {
            transaction,
        });
        

        

        

        return employee_pay_types;
    }
    

    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 employee_pay_typesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                active: item.active
            ||
            false
        
            ,
            
                effective_start: item.effective_start
            ||
            null
            ,
            
                effective_end: item.effective_end
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return employee_pay_types;
    }

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

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


        

        const updatePayload = {};
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        if (data.effective_start !== undefined) updatePayload.effective_start = data.effective_start;
        
        
        if (data.effective_end !== undefined) updatePayload.effective_end = data.effective_end;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.employee !== undefined) {
            await employee_pay_types.setEmployee(
              
              data.employee,
              
              { transaction }
            );
        }
        
        if (data.pay_type !== undefined) {
            await employee_pay_types.setPay_type(
              
              data.pay_type,
              
              { transaction }
            );
        }
        

        
        

        

        return employee_pay_types;
    }

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

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

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


        return employee_pay_types;
    }

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

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

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

        await employee_pay_types.destroy({
            transaction
        });

        return employee_pay_types;
    }

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

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

        if (employee_pay_types && isRestrictedPayrollUser(currentUser) && employee_pay_types.employeeId !== currentUser.id) {
            return null;
        }

        if (!employee_pay_types) {
            return employee_pay_types;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.employee = await employee_pay_types.getEmployee({
            transaction
        });
        
        
        output.pay_type = await employee_pay_types.getPay_type({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const currentUser = options?.currentUser;
        const effectiveEmployeeFilter = isRestrictedPayrollUser(currentUser) ? currentUser.id : filter.employee;
        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: 'employee',
        
        where: effectiveEmployeeFilter ? {
          [Op.or]: [
            { id: { [Op.in]: effectiveEmployeeFilter.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: effectiveEmployeeFilter.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : undefined,
        
      },

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



    ];

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

            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    effective_start: {
                    ...where.effective_start,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.effective_endRange) {
                const [start, end] = filter.effective_endRange;

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

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

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

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


      

      



            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.employee_pay_types.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, options) {
        const currentUser = options?.currentUser;
        let where = {};
        
        

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

        if (isRestrictedPayrollUser(currentUser)) {
            where = {
                ...where,
                employeeId: currentUser.id,
            };
        }

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

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

    
};

