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

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

        const loan_deductions = await db.loan_deductions.create(
            {
                id: data.id || undefined,
        
        amountDeducted: data.amountDeducted
        ||
        null
            ,
            
        deductionDate: data.deductionDate
        ||
        null
            ,
            
        balanceBefore: data.balanceBefore
        ||
        null
            ,
            
        balanceAfter: data.balanceAfter
        ||
        null
            ,
            
        isDeferred: data.isDeferred
        ||
        false
        
            ,
            
        deferredReason: data.deferredReason
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await loan_deductions.setLoan( data.loan || null, {
            transaction,
        });
        
        await loan_deductions.setPayrollItem( data.payrollItem || null, {
            transaction,
        });
        

        

        

        return loan_deductions;
    }
    

    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 loan_deductionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                amountDeducted: item.amountDeducted
            ||
            null
            ,
            
                deductionDate: item.deductionDate
            ||
            null
            ,
            
                balanceBefore: item.balanceBefore
            ||
            null
            ,
            
                balanceAfter: item.balanceAfter
            ||
            null
            ,
            
                isDeferred: item.isDeferred
            ||
            false
        
            ,
            
                deferredReason: item.deferredReason
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return loan_deductions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.amountDeducted !== undefined) updatePayload.amountDeducted = data.amountDeducted;
        
        
        if (data.deductionDate !== undefined) updatePayload.deductionDate = data.deductionDate;
        
        
        if (data.balanceBefore !== undefined) updatePayload.balanceBefore = data.balanceBefore;
        
        
        if (data.balanceAfter !== undefined) updatePayload.balanceAfter = data.balanceAfter;
        
        
        if (data.isDeferred !== undefined) updatePayload.isDeferred = data.isDeferred;
        
        
        if (data.deferredReason !== undefined) updatePayload.deferredReason = data.deferredReason;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.loan !== undefined) {
            await loan_deductions.setLoan(
              
              data.loan,
              
              { transaction }
            );
        }
        
        if (data.payrollItem !== undefined) {
            await loan_deductions.setPayrollItem(
              
              data.payrollItem,
              
              { transaction }
            );
        }
        

        
        

        

        return loan_deductions;
    }

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

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

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


        return loan_deductions;
    }

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

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

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

        await loan_deductions.destroy({
            transaction
        });

        return loan_deductions;
    }

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

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

        if (!loan_deductions) {
            return loan_deductions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.loan = await loan_deductions.getLoan({
            transaction
        });
        
        
        output.payrollItem = await loan_deductions.getPayrollItem({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        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.employee_loans,
        as: 'loan',
        
        where: filter.loan ? {
          [Op.or]: [
            { id: { [Op.in]: filter.loan.split('|').map(term => Utils.uuid(term)) } },
            {
              loanSource: {
                [Op.or]: filter.loan.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

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

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


      

      



            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.loan_deductions.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, ) {
        let where = {};
        
        

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

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

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

    
};

