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

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

        const payment_batches = await db.payment_batches.create(
            {
                id: data.id || undefined,
        
        batch_number: data.batch_number
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        total_amount: data.total_amount
        ||
        null
            ,
            
        scheduled_at: data.scheduled_at
        ||
        null
            ,
            
        processed_at: data.processed_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await payment_batches.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await payment_batches.setPrepared_by_user( data.prepared_by_user || null, {
            transaction,
        });
        

        

        

        return payment_batches;
    }
    

    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 payment_batchesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                batch_number: item.batch_number
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                total_amount: item.total_amount
            ||
            null
            ,
            
                scheduled_at: item.scheduled_at
            ||
            null
            ,
            
                processed_at: item.processed_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return payment_batches;
    }

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


        

        const updatePayload = {};
        
        if (data.batch_number !== undefined) updatePayload.batch_number = data.batch_number;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.total_amount !== undefined) updatePayload.total_amount = data.total_amount;
        
        
        if (data.scheduled_at !== undefined) updatePayload.scheduled_at = data.scheduled_at;
        
        
        if (data.processed_at !== undefined) updatePayload.processed_at = data.processed_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await payment_batches.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.prepared_by_user !== undefined) {
            await payment_batches.setPrepared_by_user(
              
              data.prepared_by_user,
              
              { transaction }
            );
        }
        

        
        

        

        return payment_batches;
    }

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

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

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


        return payment_batches;
    }

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

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

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

        await payment_batches.destroy({
            transaction
        });

        return payment_batches;
    }

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

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

        if (!payment_batches) {
            return payment_batches;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.payments_batch = await payment_batches.getPayments_batch({
            transaction
        });
        
        
        
        
        
        
        
        output.organization = await payment_batches.getOrganization({
            transaction
        });
        
        
        output.prepared_by_user = await payment_batches.getPrepared_by_user({
            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.organizations,
        as: 'organization',
        
      },

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



    ];

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

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

            
            

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    processed_at: {
                    ...where.processed_at,
                            [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.currency) {
                where = {
                    ...where,
                currency: filter.currency,
            };
            }
            


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

        where = {
          ...where,
          organizationId: {[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.payment_batches.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(
                        'payment_batches',
                        'batch_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

