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

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

        const usage_limits = await db.usage_limits.create(
            {
                id: data.id || undefined,
        
        feature: data.feature
        ||
        null
            ,
            
        limit_count: data.limit_count
        ||
        null
            ,
            
        used_count: data.used_count
        ||
        null
            ,
            
        window_start_at: data.window_start_at
        ||
        null
            ,
            
        window_end_at: data.window_end_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await usage_limits.setUser( data.user || null, {
            transaction,
        });
        
        await usage_limits.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return usage_limits;
    }
    

    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 usage_limitsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                feature: item.feature
            ||
            null
            ,
            
                limit_count: item.limit_count
            ||
            null
            ,
            
                used_count: item.used_count
            ||
            null
            ,
            
                window_start_at: item.window_start_at
            ||
            null
            ,
            
                window_end_at: item.window_end_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return usage_limits;
    }

    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 usage_limits = await db.usage_limits.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.feature !== undefined) updatePayload.feature = data.feature;
        
        
        if (data.limit_count !== undefined) updatePayload.limit_count = data.limit_count;
        
        
        if (data.used_count !== undefined) updatePayload.used_count = data.used_count;
        
        
        if (data.window_start_at !== undefined) updatePayload.window_start_at = data.window_start_at;
        
        
        if (data.window_end_at !== undefined) updatePayload.window_end_at = data.window_end_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return usage_limits;
    }

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

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

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


        return usage_limits;
    }

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

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

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

        await usage_limits.destroy({
            transaction
        });

        return usage_limits;
    }

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

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

        if (!usage_limits) {
            return usage_limits;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await usage_limits.getUser({
            transaction
        });
        
        
        output.organizations = await usage_limits.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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            

            
            

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

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

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

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

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

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

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

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

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

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

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


      

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

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

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

    
};

