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

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

        const usage_limit_policies = await db.usage_limit_policies.create(
            {
                id: data.id || undefined,
        
        policy_name: data.policy_name
        ||
        null
            ,
            
        scope: data.scope
        ||
        null
            ,
            
        daily_request_limit: data.daily_request_limit
        ||
        null
            ,
            
        monthly_request_limit: data.monthly_request_limit
        ||
        null
            ,
            
        daily_cost_limit: data.daily_cost_limit
        ||
        null
            ,
            
        monthly_cost_limit: data.monthly_cost_limit
        ||
        null
            ,
            
        hard_block_on_limit: data.hard_block_on_limit
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return usage_limit_policies;
    }
    

    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_limit_policiesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                policy_name: item.policy_name
            ||
            null
            ,
            
                scope: item.scope
            ||
            null
            ,
            
                daily_request_limit: item.daily_request_limit
            ||
            null
            ,
            
                monthly_request_limit: item.monthly_request_limit
            ||
            null
            ,
            
                daily_cost_limit: item.daily_cost_limit
            ||
            null
            ,
            
                monthly_cost_limit: item.monthly_cost_limit
            ||
            null
            ,
            
                hard_block_on_limit: item.hard_block_on_limit
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return usage_limit_policies;
    }

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

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


        

        const updatePayload = {};
        
        if (data.policy_name !== undefined) updatePayload.policy_name = data.policy_name;
        
        
        if (data.scope !== undefined) updatePayload.scope = data.scope;
        
        
        if (data.daily_request_limit !== undefined) updatePayload.daily_request_limit = data.daily_request_limit;
        
        
        if (data.monthly_request_limit !== undefined) updatePayload.monthly_request_limit = data.monthly_request_limit;
        
        
        if (data.daily_cost_limit !== undefined) updatePayload.daily_cost_limit = data.daily_cost_limit;
        
        
        if (data.monthly_cost_limit !== undefined) updatePayload.monthly_cost_limit = data.monthly_cost_limit;
        
        
        if (data.hard_block_on_limit !== undefined) updatePayload.hard_block_on_limit = data.hard_block_on_limit;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return usage_limit_policies;
    }

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

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

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


        return usage_limit_policies;
    }

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

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

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

        await usage_limit_policies.destroy({
            transaction
        });

        return usage_limit_policies;
    }

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

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

        if (!usage_limit_policies) {
            return usage_limit_policies;
        }

        const output = usage_limit_policies.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.policy_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'usage_limit_policies',
                        'policy_name',
                        filter.policy_name,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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




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

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

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

    
};

