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

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

        const tools = await db.tools.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        slug: data.slug
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        category: data.category
        ||
        null
            ,
            
        execution_preference: data.execution_preference
        ||
        null
            ,
            
        requires_confirmation: data.requires_confirmation
        ||
        false
        
            ,
            
        is_demo_supported: data.is_demo_supported
        ||
        false
        
            ,
            
        is_enabled: data.is_enabled
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await tools.setProvider( data.provider || null, {
            transaction,
        });
        
        await tools.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return tools;
    }
    

    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 toolsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                slug: item.slug
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                category: item.category
            ||
            null
            ,
            
                execution_preference: item.execution_preference
            ||
            null
            ,
            
                requires_confirmation: item.requires_confirmation
            ||
            false
        
            ,
            
                is_demo_supported: item.is_demo_supported
            ||
            false
        
            ,
            
                is_enabled: item.is_enabled
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return tools;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.slug !== undefined) updatePayload.slug = data.slug;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.category !== undefined) updatePayload.category = data.category;
        
        
        if (data.execution_preference !== undefined) updatePayload.execution_preference = data.execution_preference;
        
        
        if (data.requires_confirmation !== undefined) updatePayload.requires_confirmation = data.requires_confirmation;
        
        
        if (data.is_demo_supported !== undefined) updatePayload.is_demo_supported = data.is_demo_supported;
        
        
        if (data.is_enabled !== undefined) updatePayload.is_enabled = data.is_enabled;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.provider !== undefined) {
            await tools.setProvider(
              
              data.provider,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await tools.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return tools;
    }

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

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

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


        return tools;
    }

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

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

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

        await tools.destroy({
            transaction
        });

        return tools;
    }

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

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

        if (!tools) {
            return tools;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tool_actions_tool = await tools.getTool_actions_tool({
            transaction
        });
        
        
        
        
        
        
        output.tool_runs_tool = await tools.getTool_runs_tool({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.provider = await tools.getProvider({
            transaction
        });
        
        
        output.organizations = await tools.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.tool_providers,
        as: 'provider',
        
        where: filter.provider ? {
          [Op.or]: [
            { id: { [Op.in]: filter.provider.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.provider.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(
                        'tools',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.slug) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tools',
                        'slug',
                        filter.slug,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tools',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.category) {
                where = {
                    ...where,
                category: filter.category,
            };
            }
            
            if (filter.execution_preference) {
                where = {
                    ...where,
                execution_preference: filter.execution_preference,
            };
            }
            
            if (filter.requires_confirmation) {
                where = {
                    ...where,
                requires_confirmation: filter.requires_confirmation,
            };
            }
            
            if (filter.is_demo_supported) {
                where = {
                    ...where,
                is_demo_supported: filter.is_demo_supported,
            };
            }
            
            if (filter.is_enabled) {
                where = {
                    ...where,
                is_enabled: filter.is_enabled,
            };
            }
            


      

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

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

    
};

