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

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

        const server_caches = await db.server_caches.create(
            {
                id: data.id || undefined,
        
        cache_key: data.cache_key
        ||
        null
            ,
            
        cache_type: data.cache_type
        ||
        null
            ,
            
        namespace: data.namespace
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
        refreshed_at: data.refreshed_at
        ||
        null
            ,
            
        value_hash: data.value_hash
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return server_caches;
    }
    

    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 server_cachesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                cache_key: item.cache_key
            ||
            null
            ,
            
                cache_type: item.cache_type
            ||
            null
            ,
            
                namespace: item.namespace
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
                refreshed_at: item.refreshed_at
            ||
            null
            ,
            
                value_hash: item.value_hash
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return server_caches;
    }

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

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


        

        const updatePayload = {};
        
        if (data.cache_key !== undefined) updatePayload.cache_key = data.cache_key;
        
        
        if (data.cache_type !== undefined) updatePayload.cache_type = data.cache_type;
        
        
        if (data.namespace !== undefined) updatePayload.namespace = data.namespace;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        if (data.refreshed_at !== undefined) updatePayload.refreshed_at = data.refreshed_at;
        
        
        if (data.value_hash !== undefined) updatePayload.value_hash = data.value_hash;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return server_caches;
    }

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

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

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


        return server_caches;
    }

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

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

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

        await server_caches.destroy({
            transaction
        });

        return server_caches;
    }

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

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

        if (!server_caches) {
            return server_caches;
        }

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

            
            

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

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

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

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

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

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

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




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

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

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

    
};

