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

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

        const soc_agents = await db.soc_agents.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        agent_type: data.agent_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        capabilities: data.capabilities
        ||
        null
            ,
            
        approval_required_by_default: data.approval_required_by_default
        ||
        false
        
            ,
            
        last_heartbeat_at: data.last_heartbeat_at
        ||
        null
            ,
            
        actions_success_rate: data.actions_success_rate
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await soc_agents.setModel( data.model || null, {
            transaction,
        });
        
        await soc_agents.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return soc_agents;
    }
    

    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 soc_agentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                agent_type: item.agent_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                capabilities: item.capabilities
            ||
            null
            ,
            
                approval_required_by_default: item.approval_required_by_default
            ||
            false
        
            ,
            
                last_heartbeat_at: item.last_heartbeat_at
            ||
            null
            ,
            
                actions_success_rate: item.actions_success_rate
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return soc_agents;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.agent_type !== undefined) updatePayload.agent_type = data.agent_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.capabilities !== undefined) updatePayload.capabilities = data.capabilities;
        
        
        if (data.approval_required_by_default !== undefined) updatePayload.approval_required_by_default = data.approval_required_by_default;
        
        
        if (data.last_heartbeat_at !== undefined) updatePayload.last_heartbeat_at = data.last_heartbeat_at;
        
        
        if (data.actions_success_rate !== undefined) updatePayload.actions_success_rate = data.actions_success_rate;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.model !== undefined) {
            await soc_agents.setModel(
              
              data.model,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await soc_agents.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return soc_agents;
    }

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

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

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


        return soc_agents;
    }

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

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

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

        await soc_agents.destroy({
            transaction
        });

        return soc_agents;
    }

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

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

        if (!soc_agents) {
            return soc_agents;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.model = await soc_agents.getModel({
            transaction
        });
        
        
        output.organizations = await soc_agents.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'soc_agents',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.capabilities) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'soc_agents',
                        'capabilities',
                        filter.capabilities,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.agent_type) {
                where = {
                    ...where,
                agent_type: filter.agent_type,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.approval_required_by_default) {
                where = {
                    ...where,
                approval_required_by_default: filter.approval_required_by_default,
            };
            }
            


      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.soc_agents.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'soc_agents',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

