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

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

        const approval_steps = await db.approval_steps.create(
            {
                id: data.id || undefined,
        
        step_order: data.step_order
        ||
        null
            ,
            
        step_name: data.step_name
        ||
        null
            ,
            
        step_type: data.step_type
        ||
        null
            ,
            
        assignment_rule: data.assignment_rule
        ||
        null
            ,
            
        sla_days: data.sla_days
        ||
        null
            ,
            
        required: data.required
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await approval_steps.setWorkflow( data.workflow || null, {
            transaction,
        });
        
        await approval_steps.setAssignee( data.assignee || null, {
            transaction,
        });
        

        

        

        return approval_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 approval_stepsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                step_order: item.step_order
            ||
            null
            ,
            
                step_name: item.step_name
            ||
            null
            ,
            
                step_type: item.step_type
            ||
            null
            ,
            
                assignment_rule: item.assignment_rule
            ||
            null
            ,
            
                sla_days: item.sla_days
            ||
            null
            ,
            
                required: item.required
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return approval_steps;
    }

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

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


        

        const updatePayload = {};
        
        if (data.step_order !== undefined) updatePayload.step_order = data.step_order;
        
        
        if (data.step_name !== undefined) updatePayload.step_name = data.step_name;
        
        
        if (data.step_type !== undefined) updatePayload.step_type = data.step_type;
        
        
        if (data.assignment_rule !== undefined) updatePayload.assignment_rule = data.assignment_rule;
        
        
        if (data.sla_days !== undefined) updatePayload.sla_days = data.sla_days;
        
        
        if (data.required !== undefined) updatePayload.required = data.required;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.workflow !== undefined) {
            await approval_steps.setWorkflow(
              
              data.workflow,
              
              { transaction }
            );
        }
        
        if (data.assignee !== undefined) {
            await approval_steps.setAssignee(
              
              data.assignee,
              
              { transaction }
            );
        }
        

        
        

        

        return approval_steps;
    }

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

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

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


        return approval_steps;
    }

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

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

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

        await approval_steps.destroy({
            transaction
        });

        return approval_steps;
    }

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

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

        if (!approval_steps) {
            return approval_steps;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        output.approval_tasks_step = await approval_steps.getApproval_tasks_step({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.workflow = await approval_steps.getWorkflow({
            transaction
        });
        
        
        output.assignee = await approval_steps.getAssignee({
            transaction
        });
        
        

        return output;
    }

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

        

        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

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



    ];

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

            
            if (filter.step_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'approval_steps',
                        'step_name',
                        filter.step_name,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.step_type) {
                where = {
                    ...where,
                step_type: filter.step_type,
            };
            }
            
            if (filter.assignment_rule) {
                where = {
                    ...where,
                assignment_rule: filter.assignment_rule,
            };
            }
            
            if (filter.required) {
                where = {
                    ...where,
                required: filter.required,
            };
            }
            


      

      



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

        

        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.approval_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, ) {
        let where = {};
        
        

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

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

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

    
};

