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

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

        const payments = await db.payments.create(
            {
                id: data.id || undefined,
        
        payment_type: data.payment_type
        ||
        null
            ,
            
        amount_gross: data.amount_gross
        ||
        null
            ,
            
        platform_fee_client_rate: data.platform_fee_client_rate
        ||
        null
            ,
            
        platform_fee_freelancer_rate: data.platform_fee_freelancer_rate
        ||
        null
            ,
            
        platform_fee_amount: data.platform_fee_amount
        ||
        null
            ,
            
        amount_net: data.amount_net
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        provider: data.provider
        ||
        null
            ,
            
        provider_reference: data.provider_reference
        ||
        null
            ,
            
        initiated_at: data.initiated_at
        ||
        null
            ,
            
        paid_at: data.paid_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await payments.setContract( data.contract || null, {
            transaction,
        });
        
        await payments.setPayer( data.payer || null, {
            transaction,
        });
        
        await payments.setPayee( data.payee || null, {
            transaction,
        });
        

        

        

        return payments;
    }
    

    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 paymentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                payment_type: item.payment_type
            ||
            null
            ,
            
                amount_gross: item.amount_gross
            ||
            null
            ,
            
                platform_fee_client_rate: item.platform_fee_client_rate
            ||
            null
            ,
            
                platform_fee_freelancer_rate: item.platform_fee_freelancer_rate
            ||
            null
            ,
            
                platform_fee_amount: item.platform_fee_amount
            ||
            null
            ,
            
                amount_net: item.amount_net
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                provider: item.provider
            ||
            null
            ,
            
                provider_reference: item.provider_reference
            ||
            null
            ,
            
                initiated_at: item.initiated_at
            ||
            null
            ,
            
                paid_at: item.paid_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return payments;
    }

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

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


        

        const updatePayload = {};
        
        if (data.payment_type !== undefined) updatePayload.payment_type = data.payment_type;
        
        
        if (data.amount_gross !== undefined) updatePayload.amount_gross = data.amount_gross;
        
        
        if (data.platform_fee_client_rate !== undefined) updatePayload.platform_fee_client_rate = data.platform_fee_client_rate;
        
        
        if (data.platform_fee_freelancer_rate !== undefined) updatePayload.platform_fee_freelancer_rate = data.platform_fee_freelancer_rate;
        
        
        if (data.platform_fee_amount !== undefined) updatePayload.platform_fee_amount = data.platform_fee_amount;
        
        
        if (data.amount_net !== undefined) updatePayload.amount_net = data.amount_net;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.provider !== undefined) updatePayload.provider = data.provider;
        
        
        if (data.provider_reference !== undefined) updatePayload.provider_reference = data.provider_reference;
        
        
        if (data.initiated_at !== undefined) updatePayload.initiated_at = data.initiated_at;
        
        
        if (data.paid_at !== undefined) updatePayload.paid_at = data.paid_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.contract !== undefined) {
            await payments.setContract(
              
              data.contract,
              
              { transaction }
            );
        }
        
        if (data.payer !== undefined) {
            await payments.setPayer(
              
              data.payer,
              
              { transaction }
            );
        }
        
        if (data.payee !== undefined) {
            await payments.setPayee(
              
              data.payee,
              
              { transaction }
            );
        }
        

        
        

        

        return payments;
    }

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

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

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


        return payments;
    }

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

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

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

        await payments.destroy({
            transaction
        });

        return payments;
    }

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

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

        if (!payments) {
            return payments;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.invoices_payment = await payments.getInvoices_payment({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.contract = await payments.getContract({
            transaction
        });
        
        
        output.payer = await payments.getPayer({
            transaction
        });
        
        
        output.payee = await payments.getPayee({
            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.contracts,
        as: 'contract',
        
        where: filter.contract ? {
          [Op.or]: [
            { id: { [Op.in]: filter.contract.split('|').map(term => Utils.uuid(term)) } },
            {
              terms: {
                [Op.or]: filter.contract.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    initiated_at: {
                    ...where.initiated_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.payment_type) {
                where = {
                    ...where,
                payment_type: filter.payment_type,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.provider) {
                where = {
                    ...where,
                provider: filter.provider,
            };
            }
            


      

      

      



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

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

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

    
};

