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

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

        const approvals = await db.approvals.create(
            {
                id: data.id || undefined,
        
        record_type: data.record_type
        ||
        null
            ,
            
        record_key: data.record_key
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        requested_at: data.requested_at
        ||
        null
            ,
            
        decided_at: data.decided_at
        ||
        null
            ,
            
        decision_comment: data.decision_comment
        ||
        null
            ,
            
        rejection_reason: data.rejection_reason
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await approvals.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await approvals.setWorkflow( data.workflow || null, {
            transaction,
        });
        
        await approvals.setStep( data.step || null, {
            transaction,
        });
        
        await approvals.setRequested_by_user( data.requested_by_user || null, {
            transaction,
        });
        
        await approvals.setAssigned_to_user( data.assigned_to_user || null, {
            transaction,
        });
        

        

        

        return approvals;
    }
    

    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 approvalsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                record_type: item.record_type
            ||
            null
            ,
            
                record_key: item.record_key
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                requested_at: item.requested_at
            ||
            null
            ,
            
                decided_at: item.decided_at
            ||
            null
            ,
            
                decision_comment: item.decision_comment
            ||
            null
            ,
            
                rejection_reason: item.rejection_reason
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return approvals;
    }

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


        

        const updatePayload = {};
        
        if (data.record_type !== undefined) updatePayload.record_type = data.record_type;
        
        
        if (data.record_key !== undefined) updatePayload.record_key = data.record_key;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
        
        
        if (data.decided_at !== undefined) updatePayload.decided_at = data.decided_at;
        
        
        if (data.decision_comment !== undefined) updatePayload.decision_comment = data.decision_comment;
        
        
        if (data.rejection_reason !== undefined) updatePayload.rejection_reason = data.rejection_reason;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await approvals.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.workflow !== undefined) {
            await approvals.setWorkflow(
              
              data.workflow,
              
              { transaction }
            );
        }
        
        if (data.step !== undefined) {
            await approvals.setStep(
              
              data.step,
              
              { transaction }
            );
        }
        
        if (data.requested_by_user !== undefined) {
            await approvals.setRequested_by_user(
              
              data.requested_by_user,
              
              { transaction }
            );
        }
        
        if (data.assigned_to_user !== undefined) {
            await approvals.setAssigned_to_user(
              
              data.assigned_to_user,
              
              { transaction }
            );
        }
        

        
        

        

        return approvals;
    }

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

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

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


        return approvals;
    }

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

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

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

        await approvals.destroy({
            transaction
        });

        return approvals;
    }

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

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

        if (!approvals) {
            return approvals;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await approvals.getOrganization({
            transaction
        });
        
        
        output.workflow = await approvals.getWorkflow({
            transaction
        });
        
        
        output.step = await approvals.getStep({
            transaction
        });
        
        
        output.requested_by_user = await approvals.getRequested_by_user({
            transaction
        });
        
        
        output.assigned_to_user = await approvals.getAssigned_to_user({
            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.organizations,
        as: 'organization',
        
      },

      {
        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.approval_steps,
        as: 'step',
        
        where: filter.step ? {
          [Op.or]: [
            { id: { [Op.in]: filter.step.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.step.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.record_type) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'approvals',
                        'record_type',
                        filter.record_type,
                    ),
                };
            }
            
            if (filter.record_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'approvals',
                        'record_key',
                        filter.record_key,
                    ),
                };
            }
            
            if (filter.decision_comment) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'approvals',
                        'decision_comment',
                        filter.decision_comment,
                    ),
                };
            }
            
            if (filter.rejection_reason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'approvals',
                        'rejection_reason',
                        filter.rejection_reason,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    requested_at: {
                    ...where.requested_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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

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


      
      if (filter.organization) {
        const listItems = filter.organization.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationId: {[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.approvals.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(
                        'approvals',
                        'record_key',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

