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

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

        const api_request_logs = await db.api_request_logs.create(
            {
                id: data.id || undefined,
        
        provider: data.provider
        ||
        null
            ,
            
        request_method: data.request_method
        ||
        null
            ,
            
        request_path: data.request_path
        ||
        null
            ,
            
        request_query: data.request_query
        ||
        null
            ,
            
        response_status: data.response_status
        ||
        null
            ,
            
        duration_ms: data.duration_ms
        ||
        null
            ,
            
        error_message: data.error_message
        ||
        null
            ,
            
        requested_at: data.requested_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await api_request_logs.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return api_request_logs;
    }
    

    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 api_request_logsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                provider: item.provider
            ||
            null
            ,
            
                request_method: item.request_method
            ||
            null
            ,
            
                request_path: item.request_path
            ||
            null
            ,
            
                request_query: item.request_query
            ||
            null
            ,
            
                response_status: item.response_status
            ||
            null
            ,
            
                duration_ms: item.duration_ms
            ||
            null
            ,
            
                error_message: item.error_message
            ||
            null
            ,
            
                requested_at: item.requested_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return api_request_logs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.provider !== undefined) updatePayload.provider = data.provider;
        
        
        if (data.request_method !== undefined) updatePayload.request_method = data.request_method;
        
        
        if (data.request_path !== undefined) updatePayload.request_path = data.request_path;
        
        
        if (data.request_query !== undefined) updatePayload.request_query = data.request_query;
        
        
        if (data.response_status !== undefined) updatePayload.response_status = data.response_status;
        
        
        if (data.duration_ms !== undefined) updatePayload.duration_ms = data.duration_ms;
        
        
        if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
        
        
        if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return api_request_logs;
    }

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

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

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


        return api_request_logs;
    }

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

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

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

        await api_request_logs.destroy({
            transaction
        });

        return api_request_logs;
    }

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

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

        if (!api_request_logs) {
            return api_request_logs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await api_request_logs.getUser({
            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 = [

      {
        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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.request_method) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'api_request_logs',
                        'request_method',
                        filter.request_method,
                    ),
                };
            }
            
            if (filter.request_path) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'api_request_logs',
                        'request_path',
                        filter.request_path,
                    ),
                };
            }
            
            if (filter.request_query) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'api_request_logs',
                        'request_query',
                        filter.request_query,
                    ),
                };
            }
            
            if (filter.error_message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'api_request_logs',
                        'error_message',
                        filter.error_message,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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


      



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

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

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

    
};

