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

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

        const tool_runs = await db.tool_runs.create(
            {
                id: data.id || undefined,
        
        status: data.status
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        ended_at: data.ended_at
        ||
        null
            ,
            
        input_payload: data.input_payload
        ||
        null
            ,
            
        output_payload: data.output_payload
        ||
        null
            ,
            
        logs: data.logs
        ||
        null
            ,
            
        error_message: data.error_message
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return tool_runs;
    }
    

    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_runsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                status: item.status
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                ended_at: item.ended_at
            ||
            null
            ,
            
                input_payload: item.input_payload
            ||
            null
            ,
            
                output_payload: item.output_payload
            ||
            null
            ,
            
                logs: item.logs
            ||
            null
            ,
            
                error_message: item.error_message
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return tool_runs;
    }

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


        

        const updatePayload = {};
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
        
        
        if (data.input_payload !== undefined) updatePayload.input_payload = data.input_payload;
        
        
        if (data.output_payload !== undefined) updatePayload.output_payload = data.output_payload;
        
        
        if (data.logs !== undefined) updatePayload.logs = data.logs;
        
        
        if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return tool_runs;
    }

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

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

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


        return tool_runs;
    }

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

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

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

        await tool_runs.destroy({
            transaction
        });

        return tool_runs;
    }

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

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

        if (!tool_runs) {
            return tool_runs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.confirmations_tool_run = await tool_runs.getConfirmations_tool_run({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.task_step = await tool_runs.getTask_step({
            transaction
        });
        
        
        output.tool = await tool_runs.getTool({
            transaction
        });
        
        
        output.organizations = await tool_runs.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.task_steps,
        as: 'task_step',
        
        where: filter.task_step ? {
          [Op.or]: [
            { id: { [Op.in]: filter.task_step.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.task_step.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        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.input_payload) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tool_runs',
                        'input_payload',
                        filter.input_payload,
                    ),
                };
            }
            
            if (filter.output_payload) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tool_runs',
                        'output_payload',
                        filter.output_payload,
                    ),
                };
            }
            
            if (filter.logs) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tool_runs',
                        'logs',
                        filter.logs,
                    ),
                };
            }
            
            if (filter.error_message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tool_runs',
                        'error_message',
                        filter.error_message,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            started_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    ended_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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


      

      

      
      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_runs.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_runs',
                        'status',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

