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

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

        const payment_transactions = await db.payment_transactions.create(
            {
                id: data.id || undefined,
        
        status: data.status
        ||
        null
            ,
            
        provider: data.provider
        ||
        null
            ,
            
        amount_uzs: data.amount_uzs
        ||
        null
            ,
            
        provider_transaction_reference: data.provider_transaction_reference
        ||
        null
            ,
            
        failure_reason: data.failure_reason
        ||
        null
            ,
            
        initiated_at: data.initiated_at
        ||
        null
            ,
            
        finalized_at: data.finalized_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await payment_transactions.setWithdrawal_request( data.withdrawal_request || null, {
            transaction,
        });
        

        

        

        return payment_transactions;
    }
    

    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_transactionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                status: item.status
            ||
            null
            ,
            
                provider: item.provider
            ||
            null
            ,
            
                amount_uzs: item.amount_uzs
            ||
            null
            ,
            
                provider_transaction_reference: item.provider_transaction_reference
            ||
            null
            ,
            
                failure_reason: item.failure_reason
            ||
            null
            ,
            
                initiated_at: item.initiated_at
            ||
            null
            ,
            
                finalized_at: item.finalized_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return payment_transactions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.provider !== undefined) updatePayload.provider = data.provider;
        
        
        if (data.amount_uzs !== undefined) updatePayload.amount_uzs = data.amount_uzs;
        
        
        if (data.provider_transaction_reference !== undefined) updatePayload.provider_transaction_reference = data.provider_transaction_reference;
        
        
        if (data.failure_reason !== undefined) updatePayload.failure_reason = data.failure_reason;
        
        
        if (data.initiated_at !== undefined) updatePayload.initiated_at = data.initiated_at;
        
        
        if (data.finalized_at !== undefined) updatePayload.finalized_at = data.finalized_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.withdrawal_request !== undefined) {
            await payment_transactions.setWithdrawal_request(
              
              data.withdrawal_request,
              
              { transaction }
            );
        }
        

        
        

        

        return payment_transactions;
    }

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

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

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


        return payment_transactions;
    }

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

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

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

        await payment_transactions.destroy({
            transaction
        });

        return payment_transactions;
    }

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

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

        if (!payment_transactions) {
            return payment_transactions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.withdrawal_request = await payment_transactions.getWithdrawal_request({
            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.withdrawal_requests,
        as: 'withdrawal_request',
        
        where: filter.withdrawal_request ? {
          [Op.or]: [
            { id: { [Op.in]: filter.withdrawal_request.split('|').map(term => Utils.uuid(term)) } },
            {
              payout_destination: {
                [Op.or]: filter.withdrawal_request.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.provider_transaction_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'payment_transactions',
                        'provider_transaction_reference',
                        filter.provider_transaction_reference,
                    ),
                };
            }
            
            if (filter.failure_reason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'payment_transactions',
                        'failure_reason',
                        filter.failure_reason,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    amount_uzs: {
                    ...where.amount_uzs,
                            [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.finalized_atRange) {
                const [start, end] = filter.finalized_atRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    finalized_at: {
                    ...where.finalized_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.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.payment_transactions.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(
                        'payment_transactions',
                        'provider_transaction_reference',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

