
const db = require('../models');
const Utils = require('../utils');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Access_logsDBApi {
    

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

        const access_logs = await db.access_logs.create(
            {
                id: data.id || undefined,
        
        environment: data.environment
        ||
        null
            ,
            
        path: data.path
        ||
        null
            ,
            
        ip_address: data.ip_address
        ||
        null
            ,
            
        user_agent: data.user_agent
        ||
        null
            ,
            
        accessed_at: data.accessed_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await access_logs.setProject( data.project || null, {
            transaction,
        });
        
        await access_logs.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return access_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 access_logsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                environment: item.environment
            ||
            null
            ,
            
                path: item.path
            ||
            null
            ,
            
                ip_address: item.ip_address
            ||
            null
            ,
            
                user_agent: item.user_agent
            ||
            null
            ,
            
                accessed_at: item.accessed_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return access_logs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.environment !== undefined) updatePayload.environment = data.environment;
        
        
        if (data.path !== undefined) updatePayload.path = data.path;
        
        
        if (data.ip_address !== undefined) updatePayload.ip_address = data.ip_address;
        
        
        if (data.user_agent !== undefined) updatePayload.user_agent = data.user_agent;
        
        
        if (data.accessed_at !== undefined) updatePayload.accessed_at = data.accessed_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return access_logs;
    }

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

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

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


        return access_logs;
    }

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

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

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

        await access_logs.destroy({
            transaction
        });

        return access_logs;
    }

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

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

        if (!access_logs) {
            return access_logs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.project = await access_logs.getProject({
            transaction
        });
        
        
        output.user = await access_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;

    let include = [

      {
        model: db.projects,
        as: 'project',
        
        where: filter.project ? {
          [Op.or]: [
            { id: { [Op.in]: filter.project.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.project.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        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.path) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'access_logs',
                        'path',
                        filter.path,
                    ),
                };
            }
            
            if (filter.ip_address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'access_logs',
                        'ip_address',
                        filter.ip_address,
                    ),
                };
            }
            
            if (filter.user_agent) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'access_logs',
                        'user_agent',
                        filter.user_agent,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

      



            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.access_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(
                        'access_logs',
                        'path',
                        query,
                    ),
                ],
            };
        }

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

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

    
};
