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

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

        const loyalty_accounts = await db.loyalty_accounts.create(
            {
                id: data.id || undefined,
        
        points_balance: data.points_balance
        ||
        null
            ,
            
        last_activity_at: data.last_activity_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await loyalty_accounts.setClient_user( data.client_user || null, {
            transaction,
        });
        

        

        

        return loyalty_accounts;
    }
    

    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_accountsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                points_balance: item.points_balance
            ||
            null
            ,
            
                last_activity_at: item.last_activity_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return loyalty_accounts;
    }

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

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


        

        const updatePayload = {};
        
        if (data.points_balance !== undefined) updatePayload.points_balance = data.points_balance;
        
        
        if (data.last_activity_at !== undefined) updatePayload.last_activity_at = data.last_activity_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.client_user !== undefined) {
            await loyalty_accounts.setClient_user(
              
              data.client_user,
              
              { transaction }
            );
        }
        

        
        

        

        return loyalty_accounts;
    }

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

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

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


        return loyalty_accounts;
    }

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

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

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

        await loyalty_accounts.destroy({
            transaction
        });

        return loyalty_accounts;
    }

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

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

        if (!loyalty_accounts) {
            return loyalty_accounts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.loyalty_transactions_loyalty_account = await loyalty_accounts.getLoyalty_transactions_loyalty_account({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.client_user = await loyalty_accounts.getClient_user({
            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: 'client_user',
        
        where: filter.client_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.client_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.client_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            

            
            

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

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

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

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

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

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

            


      



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

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

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

    
};

