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

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

        const task_steps = await db.task_steps.create(
            {
                id: data.id || undefined,
        
        step_number: data.step_number
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        details: data.details
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        input_payload: data.input_payload
        ||
        null
            ,
            
        output_payload: data.output_payload
        ||
        null
            ,
            
        error_message: data.error_message
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await task_steps.setTask( data.task || null, {
            transaction,
        });
        
        await task_steps.setTool_action( data.tool_action || null, {
            transaction,
        });
        
        await task_steps.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return task_steps;
    }
    

    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 task_stepsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                step_number: item.step_number
            ||
            null
            ,
            
                title: item.title
            ||
            null
            ,
            
                details: item.details
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                input_payload: item.input_payload
            ||
            null
            ,
            
                output_payload: item.output_payload
            ||
            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 task_steps = await db.task_steps.bulkCreate(task_stepsData, { transaction });

        // For each item created, replace relation files
        

        return task_steps;
    }

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


        

        const updatePayload = {};
        
        if (data.step_number !== undefined) updatePayload.step_number = data.step_number;
        
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.details !== undefined) updatePayload.details = data.details;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.input_payload !== undefined) updatePayload.input_payload = data.input_payload;
        
        
        if (data.output_payload !== undefined) updatePayload.output_payload = data.output_payload;
        
        
        if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.task !== undefined) {
            await task_steps.setTask(
              
              data.task,
              
              { transaction }
            );
        }
        
        if (data.tool_action !== undefined) {
            await task_steps.setTool_action(
              
              data.tool_action,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await task_steps.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return task_steps;
    }

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

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

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


        return task_steps;
    }

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

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

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

        await task_steps.destroy({
            transaction
        });

        return task_steps;
    }

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

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

        if (!task_steps) {
            return task_steps;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tool_runs_task_step = await task_steps.getTool_runs_task_step({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.task = await task_steps.getTask({
            transaction
        });
        
        
        output.tool_action = await task_steps.getTool_action({
            transaction
        });
        
        
        output.organizations = await task_steps.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.tasks,
        as: 'task',
        
        where: filter.task ? {
          [Op.or]: [
            { id: { [Op.in]: filter.task.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.task.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.tool_actions,
        as: 'tool_action',
        
        where: filter.tool_action ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tool_action.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.tool_action.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.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'task_steps',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.details) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'task_steps',
                        'details',
                        filter.details,
                    ),
                };
            }
            
            if (filter.input_payload) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'task_steps',
                        'input_payload',
                        filter.input_payload,
                    ),
                };
            }
            
            if (filter.output_payload) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'task_steps',
                        'output_payload',
                        filter.output_payload,
                    ),
                };
            }
            
            if (filter.error_message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'task_steps',
                        'error_message',
                        filter.error_message,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    step_number: {
                    ...where.step_number,
                            [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.task_steps.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(
                        'task_steps',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

