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

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

        const loyalty_settings = await db.loyalty_settings.create(
            {
                id: data.id || undefined,
        
        earn_rate_percent: data.earn_rate_percent
        ||
        null
            ,
            
        redeem_value_per_point_iqd: data.redeem_value_per_point_iqd
        ||
        null
            ,
            
        min_points_to_redeem: data.min_points_to_redeem
        ||
        null
            ,
            
        is_enabled: data.is_enabled
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return loyalty_settings;
    }
    

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

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

        // For each item created, replace relation files
        

        return loyalty_settings;
    }

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

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


        

        const updatePayload = {};
        
        if (data.earn_rate_percent !== undefined) updatePayload.earn_rate_percent = data.earn_rate_percent;
        
        
        if (data.redeem_value_per_point_iqd !== undefined) updatePayload.redeem_value_per_point_iqd = data.redeem_value_per_point_iqd;
        
        
        if (data.min_points_to_redeem !== undefined) updatePayload.min_points_to_redeem = data.min_points_to_redeem;
        
        
        if (data.is_enabled !== undefined) updatePayload.is_enabled = data.is_enabled;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return loyalty_settings;
    }

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

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

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


        return loyalty_settings;
    }

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

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

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

        await loyalty_settings.destroy({
            transaction
        });

        return loyalty_settings;
    }

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

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

        if (!loyalty_settings) {
            return loyalty_settings;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        

        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 = [



    ];

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

            

            
            

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

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

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

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

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

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

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

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

            
            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.loyalty_settings.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_settings',
                        'redeem_value_per_point_iqd',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

