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

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

        const admin_audit_logs = await db.admin_audit_logs.create(
            {
                id: data.id || undefined,
        
        action: data.action
        ||
        null
            ,
            
        entity_name: data.entity_name
        ||
        null
            ,
            
        entity_reference: data.entity_reference
        ||
        null
            ,
            
        occurred_at: data.occurred_at
        ||
        null
            ,
            
        details: data.details
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await admin_audit_logs.setAdmin_user( data.admin_user || null, {
            transaction,
        });
        

        

        

        return admin_audit_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 admin_audit_logsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                action: item.action
            ||
            null
            ,
            
                entity_name: item.entity_name
            ||
            null
            ,
            
                entity_reference: item.entity_reference
            ||
            null
            ,
            
                occurred_at: item.occurred_at
            ||
            null
            ,
            
                details: item.details
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return admin_audit_logs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.action !== undefined) updatePayload.action = data.action;
        
        
        if (data.entity_name !== undefined) updatePayload.entity_name = data.entity_name;
        
        
        if (data.entity_reference !== undefined) updatePayload.entity_reference = data.entity_reference;
        
        
        if (data.occurred_at !== undefined) updatePayload.occurred_at = data.occurred_at;
        
        
        if (data.details !== undefined) updatePayload.details = data.details;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.admin_user !== undefined) {
            await admin_audit_logs.setAdmin_user(
              
              data.admin_user,
              
              { transaction }
            );
        }
        

        
        

        

        return admin_audit_logs;
    }

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

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

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


        return admin_audit_logs;
    }

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

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

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

        await admin_audit_logs.destroy({
            transaction
        });

        return admin_audit_logs;
    }

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

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

        if (!admin_audit_logs) {
            return admin_audit_logs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.admin_user = await admin_audit_logs.getAdmin_user({
            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: 'admin_user',
        
        where: filter.admin_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.admin_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.admin_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.entity_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'admin_audit_logs',
                        'entity_name',
                        filter.entity_name,
                    ),
                };
            }
            
            if (filter.entity_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'admin_audit_logs',
                        'entity_reference',
                        filter.entity_reference,
                    ),
                };
            }
            
            if (filter.details) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'admin_audit_logs',
                        'details',
                        filter.details,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      



            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.admin_audit_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(
                        'admin_audit_logs',
                        'entity_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

