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

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

        const loan_schedules = await db.loan_schedules.create(
            {
                id: data.id || undefined,
        
        bank_name: data.bank_name
        ||
        null
            ,
            
        payment_no: data.payment_no
        ||
        null
            ,
            
        payment_date: data.payment_date
        ||
        null
            ,
            
        payment_amount: data.payment_amount
        ||
        null
            ,
            
        principal: data.principal
        ||
        null
            ,
            
        interest: data.interest
        ||
        null
            ,
            
        remaining_balance: data.remaining_balance
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await loan_schedules.setCompany( data.company || null, {
            transaction,
        });
        
        await loan_schedules.setVehicle( data.vehicle || null, {
            transaction,
        });
        

        

        

        return loan_schedules;
    }
    

    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_schedulesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                bank_name: item.bank_name
            ||
            null
            ,
            
                payment_no: item.payment_no
            ||
            null
            ,
            
                payment_date: item.payment_date
            ||
            null
            ,
            
                payment_amount: item.payment_amount
            ||
            null
            ,
            
                principal: item.principal
            ||
            null
            ,
            
                interest: item.interest
            ||
            null
            ,
            
                remaining_balance: item.remaining_balance
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return loan_schedules;
    }

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


        

        const updatePayload = {};
        
        if (data.bank_name !== undefined) updatePayload.bank_name = data.bank_name;
        
        
        if (data.payment_no !== undefined) updatePayload.payment_no = data.payment_no;
        
        
        if (data.payment_date !== undefined) updatePayload.payment_date = data.payment_date;
        
        
        if (data.payment_amount !== undefined) updatePayload.payment_amount = data.payment_amount;
        
        
        if (data.principal !== undefined) updatePayload.principal = data.principal;
        
        
        if (data.interest !== undefined) updatePayload.interest = data.interest;
        
        
        if (data.remaining_balance !== undefined) updatePayload.remaining_balance = data.remaining_balance;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await loan_schedules.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.vehicle !== undefined) {
            await loan_schedules.setVehicle(
              
              data.vehicle,
              
              { transaction }
            );
        }
        

        
        

        

        return loan_schedules;
    }

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

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

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


        return loan_schedules;
    }

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

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

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

        await loan_schedules.destroy({
            transaction
        });

        return loan_schedules;
    }

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

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

        if (!loan_schedules) {
            return loan_schedules;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await loan_schedules.getCompany({
            transaction
        });
        
        
        output.vehicle = await loan_schedules.getVehicle({
            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 userCompanies = (user && user.companies?.id) || null;
        

        
        if (userCompanies) {
            if (options?.currentUser?.companiesId) {
                where.companiesId = options.currentUser.companiesId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.companies,
        as: 'company',
        
      },

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



    ];

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

            
            if (filter.bank_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'loan_schedules',
                        'bank_name',
                        filter.bank_name,
                    ),
                };
            }
            
            if (filter.payment_no) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'loan_schedules',
                        'payment_no',
                        filter.payment_no,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            payment_date: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    payment_date: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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

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

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

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

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

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

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


      
      if (filter.company) {
        const listItems = filter.company.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          companyId: {[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.companiesId;
        }
        

        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_schedules.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(
                        'loan_schedules',
                        'payment_no',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

