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

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

        const employee_loans = await db.employee_loans.create(
            {
                id: data.id || undefined,
        
        loanType: data.loanType
        ||
        null
            ,
            
        loanSource: data.loanSource
        ||
        null
            ,
            
        loanAmount: data.loanAmount
        ||
        null
            ,
            
        approvalDate: data.approvalDate
        ||
        null
            ,
            
        firstDeductionDate: data.firstDeductionDate
        ||
        null
            ,
            
        monthlyAmortization: data.monthlyAmortization
        ||
        null
            ,
            
        remainingBalance: data.remainingBalance
        ||
        null
            ,
            
        termsMonths: data.termsMonths
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        loanAccountNumber: data.loanAccountNumber
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await employee_loans.setEmployee( data.employee || null, {
            transaction,
        });
        

        

        

        return employee_loans;
    }
    

    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_loansData = data.map((item, index) => ({
                id: item.id || undefined,
                
                loanType: item.loanType
            ||
            null
            ,
            
                loanSource: item.loanSource
            ||
            null
            ,
            
                loanAmount: item.loanAmount
            ||
            null
            ,
            
                approvalDate: item.approvalDate
            ||
            null
            ,
            
                firstDeductionDate: item.firstDeductionDate
            ||
            null
            ,
            
                monthlyAmortization: item.monthlyAmortization
            ||
            null
            ,
            
                remainingBalance: item.remainingBalance
            ||
            null
            ,
            
                termsMonths: item.termsMonths
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                loanAccountNumber: item.loanAccountNumber
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return employee_loans;
    }

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

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


        

        const updatePayload = {};
        
        if (data.loanType !== undefined) updatePayload.loanType = data.loanType;
        
        
        if (data.loanSource !== undefined) updatePayload.loanSource = data.loanSource;
        
        
        if (data.loanAmount !== undefined) updatePayload.loanAmount = data.loanAmount;
        
        
        if (data.approvalDate !== undefined) updatePayload.approvalDate = data.approvalDate;
        
        
        if (data.firstDeductionDate !== undefined) updatePayload.firstDeductionDate = data.firstDeductionDate;
        
        
        if (data.monthlyAmortization !== undefined) updatePayload.monthlyAmortization = data.monthlyAmortization;
        
        
        if (data.remainingBalance !== undefined) updatePayload.remainingBalance = data.remainingBalance;
        
        
        if (data.termsMonths !== undefined) updatePayload.termsMonths = data.termsMonths;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.loanAccountNumber !== undefined) updatePayload.loanAccountNumber = data.loanAccountNumber;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return employee_loans;
    }

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

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

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


        return employee_loans;
    }

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

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

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

        await employee_loans.destroy({
            transaction
        });

        return employee_loans;
    }

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

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

        if (!employee_loans) {
            return employee_loans;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.loan_deductions_loan = await employee_loans.getLoan_deductions_loan({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.employee = await employee_loans.getEmployee({
            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.employees,
        as: 'employee',
        
        where: filter.employee ? {
          [Op.or]: [
            { id: { [Op.in]: filter.employee.split('|').map(term => Utils.uuid(term)) } },
            {
              employeeCode: {
                [Op.or]: filter.employee.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.loanSource) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employee_loans',
                        'loanSource',
                        filter.loanSource,
                    ),
                };
            }
            
            if (filter.loanAccountNumber) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employee_loans',
                        'loanAccountNumber',
                        filter.loanAccountNumber,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


      



            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_loans.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(
                        'employee_loans',
                        'loanSource',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

