
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,
        
        payout_reference: data.payout_reference
        ||
        null
            ,
            
        payout_method: data.payout_method
        ||
        null
            ,
            
        payout_status: data.payout_status
        ||
        null
            ,
            
        gross_amount: data.gross_amount
        ||
        null
            ,
            
        fee_amount: data.fee_amount
        ||
        null
            ,
            
        net_amount: data.net_amount
        ||
        null
            ,
            
        scheduled_at: data.scheduled_at
        ||
        null
            ,
            
        processed_at: data.processed_at
        ||
        null
            ,
            
        paid_at: data.paid_at
        ||
        null
            ,
            
        note: data.note
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await payouts.setTenant( data.tenant || null, {
            transaction,
        });
        
        await payouts.setRecipient_user( data.recipient_user || null, {
            transaction,
        });
        
        await payouts.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.payouts.getTableName(),
                belongsToColumn: 'payout_proof_files',
                belongsToId: payouts.id,
            },
            data.payout_proof_files,
            options,
        );
        

        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,
                
                payout_reference: item.payout_reference
            ||
            null
            ,
            
                payout_method: item.payout_method
            ||
            null
            ,
            
                payout_status: item.payout_status
            ||
            null
            ,
            
                gross_amount: item.gross_amount
            ||
            null
            ,
            
                fee_amount: item.fee_amount
            ||
            null
            ,
            
                net_amount: item.net_amount
            ||
            null
            ,
            
                scheduled_at: item.scheduled_at
            ||
            null
            ,
            
                processed_at: item.processed_at
            ||
            null
            ,
            
                paid_at: item.paid_at
            ||
            null
            ,
            
                note: item.note
            ||
            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
        
        for (let i = 0; i < payouts.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.payouts.getTableName(),
                    belongsToColumn: 'payout_proof_files',
                    belongsToId: payouts[i].id,
                },
                data[i].payout_proof_files,
                options,
            );
        }
        

        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.payout_reference !== undefined) updatePayload.payout_reference = data.payout_reference;
        
        
        if (data.payout_method !== undefined) updatePayload.payout_method = data.payout_method;
        
        
        if (data.payout_status !== undefined) updatePayload.payout_status = data.payout_status;
        
        
        if (data.gross_amount !== undefined) updatePayload.gross_amount = data.gross_amount;
        
        
        if (data.fee_amount !== undefined) updatePayload.fee_amount = data.fee_amount;
        
        
        if (data.net_amount !== undefined) updatePayload.net_amount = data.net_amount;
        
        
        if (data.scheduled_at !== undefined) updatePayload.scheduled_at = data.scheduled_at;
        
        
        if (data.processed_at !== undefined) updatePayload.processed_at = data.processed_at;
        
        
        if (data.paid_at !== undefined) updatePayload.paid_at = data.paid_at;
        
        
        if (data.note !== undefined) updatePayload.note = data.note;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await payouts.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.recipient_user !== undefined) {
            await payouts.setRecipient_user(
              
              data.recipient_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await payouts.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.payouts.getTableName(),
                belongsToColumn: 'payout_proof_files',
                belongsToId: payouts.id,
            },
            data.payout_proof_files,
            options,
        );
        

        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.tenant = await payouts.getTenant({
            transaction
        });
        
        
        output.recipient_user = await payouts.getRecipient_user({
            transaction
        });
        
        
        output.payout_proof_files = await payouts.getPayout_proof_files({
            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.tenants,
        as: 'tenant',
        
        where: filter.tenant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
            {
              tenant_name: {
                [Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



      {
        model: db.file,
        as: 'payout_proof_files',
      },

    ];

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

            
            if (filter.payout_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'payouts',
                        'payout_reference',
                        filter.payout_reference,
                    ),
                };
            }
            
            if (filter.note) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'payouts',
                        'note',
                        filter.note,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    net_amount: {
                    ...where.net_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.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.payout_method) {
                where = {
                    ...where,
                payout_method: filter.payout_method,
            };
            }
            
            if (filter.payout_status) {
                where = {
                    ...where,
                payout_status: filter.payout_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,
        }));
    }

    
};

