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

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

        const approval_workflows = await db.approval_workflows.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        applies_to: data.applies_to
        ||
        null
            ,
            
        requires_esignature: data.requires_esignature
        ||
        false
        
            ,
            
        requires_two_factor: data.requires_two_factor
        ||
        false
        
            ,
            
        min_approvals: data.min_approvals
        ||
        null
            ,
            
        instructions: data.instructions
        ||
        null
            ,
            
        active: data.active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return approval_workflows;
    }
    

    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_workflowsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                applies_to: item.applies_to
            ||
            null
            ,
            
                requires_esignature: item.requires_esignature
            ||
            false
        
            ,
            
                requires_two_factor: item.requires_two_factor
            ||
            false
        
            ,
            
                min_approvals: item.min_approvals
            ||
            null
            ,
            
                instructions: item.instructions
            ||
            null
            ,
            
                active: item.active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return approval_workflows;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.applies_to !== undefined) updatePayload.applies_to = data.applies_to;
        
        
        if (data.requires_esignature !== undefined) updatePayload.requires_esignature = data.requires_esignature;
        
        
        if (data.requires_two_factor !== undefined) updatePayload.requires_two_factor = data.requires_two_factor;
        
        
        if (data.min_approvals !== undefined) updatePayload.min_approvals = data.min_approvals;
        
        
        if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return approval_workflows;
    }

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

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

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


        return approval_workflows;
    }

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

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

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

        await approval_workflows.destroy({
            transaction
        });

        return approval_workflows;
    }

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

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

        if (!approval_workflows) {
            return approval_workflows;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.approval_steps_workflow = await approval_workflows.getApproval_steps_workflow({
            transaction
        });
        
        
        output.approval_tasks_workflow = await approval_workflows.getApproval_tasks_workflow({
            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 = [



    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'approval_workflows',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.instructions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'approval_workflows',
                        'instructions',
                        filter.instructions,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.applies_to) {
                where = {
                    ...where,
                applies_to: filter.applies_to,
            };
            }
            
            if (filter.requires_esignature) {
                where = {
                    ...where,
                requires_esignature: filter.requires_esignature,
            };
            }
            
            if (filter.requires_two_factor) {
                where = {
                    ...where,
                requires_two_factor: filter.requires_two_factor,
            };
            }
            
            if (filter.active) {
                where = {
                    ...where,
                active: filter.active,
            };
            }
            




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

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

    
};

