
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,
        
        level: data.level
        ||
        null
            ,
            
        decision: data.decision
        ||
        null
            ,
            
        comment: data.comment
        ||
        null
            ,
            
        assigned_at: data.assigned_at
        ||
        null
            ,
            
        decided_at: data.decided_at
        ||
        null
            ,
            
        sla_due_at: data.sla_due_at
        ||
        null
            ,
            
        sla_breached: data.sla_breached
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await approval_steps.setTenant( data.tenant || null, {
            transaction,
        });
        
        await approval_steps.setRequisition( data.requisition || null, {
            transaction,
        });
        
        await approval_steps.setAssigned_approver( data.assigned_approver || 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,
                
                level: item.level
            ||
            null
            ,
            
                decision: item.decision
            ||
            null
            ,
            
                comment: item.comment
            ||
            null
            ,
            
                assigned_at: item.assigned_at
            ||
            null
            ,
            
                decided_at: item.decided_at
            ||
            null
            ,
            
                sla_due_at: item.sla_due_at
            ||
            null
            ,
            
                sla_breached: item.sla_breached
            ||
            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.level !== undefined) updatePayload.level = data.level;
        
        
        if (data.decision !== undefined) updatePayload.decision = data.decision;
        
        
        if (data.comment !== undefined) updatePayload.comment = data.comment;
        
        
        if (data.assigned_at !== undefined) updatePayload.assigned_at = data.assigned_at;
        
        
        if (data.decided_at !== undefined) updatePayload.decided_at = data.decided_at;
        
        
        if (data.sla_due_at !== undefined) updatePayload.sla_due_at = data.sla_due_at;
        
        
        if (data.sla_breached !== undefined) updatePayload.sla_breached = data.sla_breached;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await approval_steps.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.requisition !== undefined) {
            await approval_steps.setRequisition(
              
              data.requisition,
              
              { transaction }
            );
        }
        
        if (data.assigned_approver !== undefined) {
            await approval_steps.setAssigned_approver(
              
              data.assigned_approver,
              
              { 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.tenant = await approval_steps.getTenant({
            transaction
        });
        
        
        output.requisition = await approval_steps.getRequisition({
            transaction
        });
        
        
        output.assigned_approver = await approval_steps.getAssigned_approver({
            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.tenants,
        as: 'tenant',
        
        where: filter.tenant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.users,
        as: 'assigned_approver',
        
        where: filter.assigned_approver ? {
          [Op.or]: [
            { id: { [Op.in]: filter.assigned_approver.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.assigned_approver.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.comment) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'approval_steps',
                        'comment',
                        filter.comment,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.level) {
                where = {
                    ...where,
                level: filter.level,
            };
            }
            
            if (filter.decision) {
                where = {
                    ...where,
                decision: filter.decision,
            };
            }
            
            if (filter.sla_breached) {
                where = {
                    ...where,
                sla_breached: filter.sla_breached,
            };
            }
            


      

      

      

      
      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',
                        'level',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

