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

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

        const withdrawal_requests = await db.withdrawal_requests.create(
            {
                id: data.id || undefined,
        
        status: data.status
        ||
        null
            ,
            
        coins_amount: data.coins_amount
        ||
        null
            ,
            
        cash_amount_uzs: data.cash_amount_uzs
        ||
        null
            ,
            
        payout_method: data.payout_method
        ||
        null
            ,
            
        payout_destination: data.payout_destination
        ||
        null
            ,
            
        provider_reference: data.provider_reference
        ||
        null
            ,
            
        admin_note: data.admin_note
        ||
        null
            ,
            
        requested_at: data.requested_at
        ||
        null
            ,
            
        processed_at: data.processed_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await withdrawal_requests.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return withdrawal_requests;
    }
    

    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 withdrawal_requestsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                status: item.status
            ||
            null
            ,
            
                coins_amount: item.coins_amount
            ||
            null
            ,
            
                cash_amount_uzs: item.cash_amount_uzs
            ||
            null
            ,
            
                payout_method: item.payout_method
            ||
            null
            ,
            
                payout_destination: item.payout_destination
            ||
            null
            ,
            
                provider_reference: item.provider_reference
            ||
            null
            ,
            
                admin_note: item.admin_note
            ||
            null
            ,
            
                requested_at: item.requested_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 withdrawal_requests = await db.withdrawal_requests.bulkCreate(withdrawal_requestsData, { transaction });

        // For each item created, replace relation files
        

        return withdrawal_requests;
    }

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

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


        

        const updatePayload = {};
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.coins_amount !== undefined) updatePayload.coins_amount = data.coins_amount;
        
        
        if (data.cash_amount_uzs !== undefined) updatePayload.cash_amount_uzs = data.cash_amount_uzs;
        
        
        if (data.payout_method !== undefined) updatePayload.payout_method = data.payout_method;
        
        
        if (data.payout_destination !== undefined) updatePayload.payout_destination = data.payout_destination;
        
        
        if (data.provider_reference !== undefined) updatePayload.provider_reference = data.provider_reference;
        
        
        if (data.admin_note !== undefined) updatePayload.admin_note = data.admin_note;
        
        
        if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
        
        
        if (data.processed_at !== undefined) updatePayload.processed_at = data.processed_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await withdrawal_requests.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

        

        return withdrawal_requests;
    }

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

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

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


        return withdrawal_requests;
    }

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

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

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

        await withdrawal_requests.destroy({
            transaction
        });

        return withdrawal_requests;
    }

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

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

        if (!withdrawal_requests) {
            return withdrawal_requests;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.payment_transactions_withdrawal_request = await withdrawal_requests.getPayment_transactions_withdrawal_request({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await withdrawal_requests.getUser({
            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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

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

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

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

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

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


      



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

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

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

    
};

