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

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

        const loyalty_transactions = await db.loyalty_transactions.create(
            {
                id: data.id || undefined,
        
        transaction_type: data.transaction_type
        ||
        null
            ,
            
        points: data.points
        ||
        null
            ,
            
        transaction_time: data.transaction_time
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await loyalty_transactions.setLoyalty_account( data.loyalty_account || null, {
            transaction,
        });
        
        await loyalty_transactions.setPayment( data.payment || null, {
            transaction,
        });
        

        

        

        return loyalty_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 loyalty_transactionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                transaction_type: item.transaction_type
            ||
            null
            ,
            
                points: item.points
            ||
            null
            ,
            
                transaction_time: item.transaction_time
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return loyalty_transactions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.transaction_type !== undefined) updatePayload.transaction_type = data.transaction_type;
        
        
        if (data.points !== undefined) updatePayload.points = data.points;
        
        
        if (data.transaction_time !== undefined) updatePayload.transaction_time = data.transaction_time;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.loyalty_account !== undefined) {
            await loyalty_transactions.setLoyalty_account(
              
              data.loyalty_account,
              
              { transaction }
            );
        }
        
        if (data.payment !== undefined) {
            await loyalty_transactions.setPayment(
              
              data.payment,
              
              { transaction }
            );
        }
        

        
        

        

        return loyalty_transactions;
    }

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

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

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


        return loyalty_transactions;
    }

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

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

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

        await loyalty_transactions.destroy({
            transaction
        });

        return loyalty_transactions;
    }

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

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

        if (!loyalty_transactions) {
            return loyalty_transactions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.loyalty_account = await loyalty_transactions.getLoyalty_account({
            transaction
        });
        
        
        output.payment = await loyalty_transactions.getPayment({
            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.loyalty_accounts,
        as: 'loyalty_account',
        
        where: filter.loyalty_account ? {
          [Op.or]: [
            { id: { [Op.in]: filter.loyalty_account.split('|').map(term => Utils.uuid(term)) } },
            {
              points_balance: {
                [Op.or]: filter.loyalty_account.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    transaction_time: {
                    ...where.transaction_time,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

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

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


      

      



            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.loyalty_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(
                        'loyalty_transactions',
                        'transaction_type',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

