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

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

        const membership_plans = await db.membership_plans.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        tier: data.tier
        ||
        null
            ,
            
        monthly_doodlecoins: data.monthly_doodlecoins
        ||
        null
            ,
            
        doodlecoin_multiplier: data.doodlecoin_multiplier
        ||
        null
            ,
            
        price_supercharged: data.price_supercharged
        ||
        null
            ,
            
        perks_summary: data.perks_summary
        ||
        null
            ,
            
        active: data.active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return membership_plans;
    }
    

    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 membership_plansData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                tier: item.tier
            ||
            null
            ,
            
                monthly_doodlecoins: item.monthly_doodlecoins
            ||
            null
            ,
            
                doodlecoin_multiplier: item.doodlecoin_multiplier
            ||
            null
            ,
            
                price_supercharged: item.price_supercharged
            ||
            null
            ,
            
                perks_summary: item.perks_summary
            ||
            null
            ,
            
                active: item.active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return membership_plans;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.tier !== undefined) updatePayload.tier = data.tier;
        
        
        if (data.monthly_doodlecoins !== undefined) updatePayload.monthly_doodlecoins = data.monthly_doodlecoins;
        
        
        if (data.doodlecoin_multiplier !== undefined) updatePayload.doodlecoin_multiplier = data.doodlecoin_multiplier;
        
        
        if (data.price_supercharged !== undefined) updatePayload.price_supercharged = data.price_supercharged;
        
        
        if (data.perks_summary !== undefined) updatePayload.perks_summary = data.perks_summary;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return membership_plans;
    }

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

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

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


        return membership_plans;
    }

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

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

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

        await membership_plans.destroy({
            transaction
        });

        return membership_plans;
    }

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

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

        if (!membership_plans) {
            return membership_plans;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.user_memberships_membership_plan = await membership_plans.getUser_memberships_membership_plan({
            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 = [



    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'membership_plans',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.perks_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'membership_plans',
                        'perks_summary',
                        filter.perks_summary,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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




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

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

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

    
};

