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

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

        const tool_actions = await db.tool_actions.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        action_key: data.action_key
        ||
        null
            ,
            
        input_schema: data.input_schema
        ||
        null
            ,
            
        output_schema: data.output_schema
        ||
        null
            ,
            
        is_enabled: data.is_enabled
        ||
        false
        
            ,
            
        is_dangerous: data.is_dangerous
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await tool_actions.setTool( data.tool || null, {
            transaction,
        });
        
        await tool_actions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return tool_actions;
    }
    

    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 tool_actionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                action_key: item.action_key
            ||
            null
            ,
            
                input_schema: item.input_schema
            ||
            null
            ,
            
                output_schema: item.output_schema
            ||
            null
            ,
            
                is_enabled: item.is_enabled
            ||
            false
        
            ,
            
                is_dangerous: item.is_dangerous
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return tool_actions;
    }

    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 tool_actions = await db.tool_actions.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.action_key !== undefined) updatePayload.action_key = data.action_key;
        
        
        if (data.input_schema !== undefined) updatePayload.input_schema = data.input_schema;
        
        
        if (data.output_schema !== undefined) updatePayload.output_schema = data.output_schema;
        
        
        if (data.is_enabled !== undefined) updatePayload.is_enabled = data.is_enabled;
        
        
        if (data.is_dangerous !== undefined) updatePayload.is_dangerous = data.is_dangerous;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tool !== undefined) {
            await tool_actions.setTool(
              
              data.tool,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await tool_actions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return tool_actions;
    }

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

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

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


        return tool_actions;
    }

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

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

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

        await tool_actions.destroy({
            transaction
        });

        return tool_actions;
    }

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

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

        if (!tool_actions) {
            return tool_actions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.task_steps_tool_action = await tool_actions.getTask_steps_tool_action({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tool = await tool_actions.getTool({
            transaction
        });
        
        
        output.organizations = await tool_actions.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.tools,
        as: 'tool',
        
        where: filter.tool ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tool.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.tool.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(
                        'tool_actions',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.action_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tool_actions',
                        'action_key',
                        filter.action_key,
                    ),
                };
            }
            
            if (filter.input_schema) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tool_actions',
                        'input_schema',
                        filter.input_schema,
                    ),
                };
            }
            
            if (filter.output_schema) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tool_actions',
                        'output_schema',
                        filter.output_schema,
                    ),
                };
            }
            

            
            

            

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

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


      

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

        const records = await db.tool_actions.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,
        }));
    }

    
};

