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

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

        const payouts = await db.payouts.create(
            {
                id: data.id || undefined,
        
        beneficiary_type: data.beneficiary_type
        ||
        null
            ,
            
        amount: data.amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        payout_method: data.payout_method
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        payout_reference: data.payout_reference
        ||
        null
            ,
            
        requested_at: data.requested_at
        ||
        null
            ,
            
        paid_at: data.paid_at
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await payouts.setBeneficiary_user( data.beneficiary_user || null, {
            transaction,
        });
        
        await payouts.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return payouts;
    }
    

    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 payoutsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                beneficiary_type: item.beneficiary_type
            ||
            null
            ,
            
                amount: item.amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                payout_method: item.payout_method
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                payout_reference: item.payout_reference
            ||
            null
            ,
            
                requested_at: item.requested_at
            ||
            null
            ,
            
                paid_at: item.paid_at
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return payouts;
    }

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


        

        const updatePayload = {};
        
        if (data.beneficiary_type !== undefined) updatePayload.beneficiary_type = data.beneficiary_type;
        
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.payout_method !== undefined) updatePayload.payout_method = data.payout_method;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.payout_reference !== undefined) updatePayload.payout_reference = data.payout_reference;
        
        
        if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
        
        
        if (data.paid_at !== undefined) updatePayload.paid_at = data.paid_at;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.beneficiary_user !== undefined) {
            await payouts.setBeneficiary_user(
              
              data.beneficiary_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await payouts.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return payouts;
    }

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

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

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


        return payouts;
    }

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

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

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

        await payouts.destroy({
            transaction
        });

        return payouts;
    }

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

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

        if (!payouts) {
            return payouts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.beneficiary_user = await payouts.getBeneficiary_user({
            transaction
        });
        
        
        output.organizations = await payouts.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.users,
        as: 'beneficiary_user',
        
        where: filter.beneficiary_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.beneficiary_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.beneficiary_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.currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'payouts',
                        'currency',
                        filter.currency,
                    ),
                };
            }
            
            if (filter.payout_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'payouts',
                        'payout_reference',
                        filter.payout_reference,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'payouts',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

            
            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.requested_atRange) {
                const [start, end] = filter.requested_atRange;

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

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

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

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

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

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


      

      
      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.payouts.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(
                        'payouts',
                        'payout_reference',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

