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

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

        const payment_methods = await db.payment_methods.create(
            {
                id: data.id || undefined,
        
        provider: data.provider
        ||
        null
            ,
            
        display_name: data.display_name
        ||
        null
            ,
            
        is_enabled: data.is_enabled
        ||
        false
        
            ,
            
        instructions: data.instructions
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

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

        return payment_methods;
    }
    

    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_methodsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                provider: item.provider
            ||
            null
            ,
            
                display_name: item.display_name
            ||
            null
            ,
            
                is_enabled: item.is_enabled
            ||
            false
        
            ,
            
                instructions: item.instructions
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < payment_methods.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.payment_methods.getTableName(),
                    belongsToColumn: 'qr_images',
                    belongsToId: payment_methods[i].id,
                },
                data[i].qr_images,
                options,
            );
        }
        

        return payment_methods;
    }

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

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


        

        const updatePayload = {};
        
        if (data.provider !== undefined) updatePayload.provider = data.provider;
        
        
        if (data.display_name !== undefined) updatePayload.display_name = data.display_name;
        
        
        if (data.is_enabled !== undefined) updatePayload.is_enabled = data.is_enabled;
        
        
        if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

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

        return payment_methods;
    }

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

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

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


        return payment_methods;
    }

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

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

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

        await payment_methods.destroy({
            transaction
        });

        return payment_methods;
    }

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

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

        if (!payment_methods) {
            return payment_methods;
        }

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

        
        
        
        
        
        
        
        
        
        
        output.payments_payment_method = await payment_methods.getPayments_payment_method({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.qr_images = await payment_methods.getQr_images({
            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.file,
        as: 'qr_images',
      },

    ];

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

            
            if (filter.display_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'payment_methods',
                        'display_name',
                        filter.display_name,
                    ),
                };
            }
            
            if (filter.instructions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'payment_methods',
                        'instructions',
                        filter.instructions,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.provider) {
                where = {
                    ...where,
                provider: filter.provider,
            };
            }
            
            if (filter.is_enabled) {
                where = {
                    ...where,
                is_enabled: filter.is_enabled,
            };
            }
            




            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_methods.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_methods',
                        'display_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

