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

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

        const payroll_adjustments = await db.payroll_adjustments.create(
            {
                id: data.id || undefined,
        
        category: data.category
        ||
        null
            ,
            
        adjustment_type: data.adjustment_type
        ||
        null
            ,
            
        amount: data.amount
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        effective_at: data.effective_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await payroll_adjustments.setPayroll_item( data.payroll_item || null, {
            transaction,
        });
        
        await payroll_adjustments.setCreated_by_user( data.created_by_user || null, {
            transaction,
        });
        
        await payroll_adjustments.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return payroll_adjustments;
    }
    

    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 payroll_adjustmentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                category: item.category
            ||
            null
            ,
            
                adjustment_type: item.adjustment_type
            ||
            null
            ,
            
                amount: item.amount
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                effective_at: item.effective_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return payroll_adjustments;
    }

    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 payroll_adjustments = await db.payroll_adjustments.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.category !== undefined) updatePayload.category = data.category;
        
        
        if (data.adjustment_type !== undefined) updatePayload.adjustment_type = data.adjustment_type;
        
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.effective_at !== undefined) updatePayload.effective_at = data.effective_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.payroll_item !== undefined) {
            await payroll_adjustments.setPayroll_item(
              
              data.payroll_item,
              
              { transaction }
            );
        }
        
        if (data.created_by_user !== undefined) {
            await payroll_adjustments.setCreated_by_user(
              
              data.created_by_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await payroll_adjustments.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return payroll_adjustments;
    }

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

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

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


        return payroll_adjustments;
    }

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

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

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

        await payroll_adjustments.destroy({
            transaction
        });

        return payroll_adjustments;
    }

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

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

        if (!payroll_adjustments) {
            return payroll_adjustments;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.payroll_item = await payroll_adjustments.getPayroll_item({
            transaction
        });
        
        
        output.created_by_user = await payroll_adjustments.getCreated_by_user({
            transaction
        });
        
        
        output.organizations = await payroll_adjustments.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.payroll_items,
        as: 'payroll_item',
        
        where: filter.payroll_item ? {
          [Op.or]: [
            { id: { [Op.in]: filter.payroll_item.split('|').map(term => Utils.uuid(term)) } },
            {
              adjustment_notes: {
                [Op.or]: filter.payroll_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'created_by_user',
        
        where: filter.created_by_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.created_by_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.created_by_user.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.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'payroll_adjustments',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.category) {
                where = {
                    ...where,
                category: filter.category,
            };
            }
            
            if (filter.adjustment_type) {
                where = {
                    ...where,
                adjustment_type: filter.adjustment_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.payroll_adjustments.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(
                        'payroll_adjustments',
                        'description',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

