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

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

        const subscription_plans = await db.subscription_plans.create(
            {
                id: data.id || undefined,
        
        plan_name: data.plan_name
        ||
        null
            ,
            
        plan_tier: data.plan_tier
        ||
        null
            ,
            
        price_monthly: data.price_monthly
        ||
        null
            ,
            
        price_yearly: data.price_yearly
        ||
        null
            ,
            
        max_users: data.max_users
        ||
        null
            ,
            
        max_branches: data.max_branches
        ||
        null
            ,
            
        max_documents: data.max_documents
        ||
        null
            ,
            
        ai_assistant_enabled: data.ai_assistant_enabled
        ||
        false
        
            ,
            
        whatsapp_alerts_enabled: data.whatsapp_alerts_enabled
        ||
        false
        
            ,
            
        custom_rules_enabled: data.custom_rules_enabled
        ||
        false
        
            ,
            
        features_note: data.features_note
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await subscription_plans.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return subscription_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 subscription_plansData = data.map((item, index) => ({
                id: item.id || undefined,
                
                plan_name: item.plan_name
            ||
            null
            ,
            
                plan_tier: item.plan_tier
            ||
            null
            ,
            
                price_monthly: item.price_monthly
            ||
            null
            ,
            
                price_yearly: item.price_yearly
            ||
            null
            ,
            
                max_users: item.max_users
            ||
            null
            ,
            
                max_branches: item.max_branches
            ||
            null
            ,
            
                max_documents: item.max_documents
            ||
            null
            ,
            
                ai_assistant_enabled: item.ai_assistant_enabled
            ||
            false
        
            ,
            
                whatsapp_alerts_enabled: item.whatsapp_alerts_enabled
            ||
            false
        
            ,
            
                custom_rules_enabled: item.custom_rules_enabled
            ||
            false
        
            ,
            
                features_note: item.features_note
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return subscription_plans;
    }

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

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


        

        const updatePayload = {};
        
        if (data.plan_name !== undefined) updatePayload.plan_name = data.plan_name;
        
        
        if (data.plan_tier !== undefined) updatePayload.plan_tier = data.plan_tier;
        
        
        if (data.price_monthly !== undefined) updatePayload.price_monthly = data.price_monthly;
        
        
        if (data.price_yearly !== undefined) updatePayload.price_yearly = data.price_yearly;
        
        
        if (data.max_users !== undefined) updatePayload.max_users = data.max_users;
        
        
        if (data.max_branches !== undefined) updatePayload.max_branches = data.max_branches;
        
        
        if (data.max_documents !== undefined) updatePayload.max_documents = data.max_documents;
        
        
        if (data.ai_assistant_enabled !== undefined) updatePayload.ai_assistant_enabled = data.ai_assistant_enabled;
        
        
        if (data.whatsapp_alerts_enabled !== undefined) updatePayload.whatsapp_alerts_enabled = data.whatsapp_alerts_enabled;
        
        
        if (data.custom_rules_enabled !== undefined) updatePayload.custom_rules_enabled = data.custom_rules_enabled;
        
        
        if (data.features_note !== undefined) updatePayload.features_note = data.features_note;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organizations !== undefined) {
            await subscription_plans.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return subscription_plans;
    }

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

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

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


        return subscription_plans;
    }

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

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

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

        await subscription_plans.destroy({
            transaction
        });

        return subscription_plans;
    }

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

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

        if (!subscription_plans) {
            return subscription_plans;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company_subscriptions_plan = await subscription_plans.getCompany_subscriptions_plan({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.organizations = await subscription_plans.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.plan_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'subscription_plans',
                        'plan_name',
                        filter.plan_name,
                    ),
                };
            }
            
            if (filter.features_note) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'subscription_plans',
                        'features_note',
                        filter.features_note,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.plan_tier) {
                where = {
                    ...where,
                plan_tier: filter.plan_tier,
            };
            }
            
            if (filter.ai_assistant_enabled) {
                where = {
                    ...where,
                ai_assistant_enabled: filter.ai_assistant_enabled,
            };
            }
            
            if (filter.whatsapp_alerts_enabled) {
                where = {
                    ...where,
                whatsapp_alerts_enabled: filter.whatsapp_alerts_enabled,
            };
            }
            
            if (filter.custom_rules_enabled) {
                where = {
                    ...where,
                custom_rules_enabled: filter.custom_rules_enabled,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.subscription_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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'subscription_plans',
                        'plan_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

