
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
            ,
            
        name: data.name
        ||
        null
            ,
            
        min_amount: data.min_amount
        ||
        null
            ,
            
        max_amount: data.max_amount
        ||
        null
            ,
            
        requires_comment: data.requires_comment
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await approval_steps.setWorkflow( data.workflow || null, {
            transaction,
        });
        
        await approval_steps.setApprover_role( data.approver_role || null, {
            transaction,
        });
        
        await approval_steps.setApprover_department( data.approver_department || null, {
            transaction,
        });
        
        await approval_steps.setOrganizations( data.organizations || 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
            ,
            
                name: item.name
            ||
            null
            ,
            
                min_amount: item.min_amount
            ||
            null
            ,
            
                max_amount: item.max_amount
            ||
            null
            ,
            
                requires_comment: item.requires_comment
            ||
            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 globalAccess = currentUser.app_role?.globalAccess;

        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.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.min_amount !== undefined) updatePayload.min_amount = data.min_amount;
        
        
        if (data.max_amount !== undefined) updatePayload.max_amount = data.max_amount;
        
        
        if (data.requires_comment !== undefined) updatePayload.requires_comment = data.requires_comment;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.workflow !== undefined) {
            await approval_steps.setWorkflow(
              
              data.workflow,
              
              { transaction }
            );
        }
        
        if (data.approver_role !== undefined) {
            await approval_steps.setApprover_role(
              
              data.approver_role,
              
              { transaction }
            );
        }
        
        if (data.approver_department !== undefined) {
            await approval_steps.setApprover_department(
              
              data.approver_department,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await approval_steps.setOrganizations(
              
              data.organizations,
              
              { 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.approvals_step = await approval_steps.getApprovals_step({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.workflow = await approval_steps.getWorkflow({
            transaction
        });
        
        
        output.approver_role = await approval_steps.getApprover_role({
            transaction
        });
        
        
        output.approver_department = await approval_steps.getApprover_department({
            transaction
        });
        
        
        output.organizations = await approval_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.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.roles,
        as: 'approver_role',
        
        where: filter.approver_role ? {
          [Op.or]: [
            { id: { [Op.in]: filter.approver_role.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.approver_role.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.departments,
        as: 'approver_department',
        
        where: filter.approver_department ? {
          [Op.or]: [
            { id: { [Op.in]: filter.approver_department.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.approver_department.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(
                        'approval_steps',
                        'name',
                        filter.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.min_amountRange) {
                const [start, end] = filter.min_amountRange;

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

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

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

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

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

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


      

      

      

      
      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.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

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

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

    
};

