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

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

        const approval_requests = await db.approval_requests.create(
            {
                id: data.id || undefined,
        
        requestType: data.requestType
        ||
        null
            ,
            
        entityId: data.entityId
        ||
        null
            ,
            
        entityType: data.entityType
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        requestedAt: data.requestedAt
        ||
        null
            ,
            
        approvedAt: data.approvedAt
        ||
        null
            ,
            
        rejectedAt: data.rejectedAt
        ||
        null
            ,
            
        rejectionReason: data.rejectionReason
        ||
        null
            ,
            
        amount: data.amount
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await approval_requests.setRequestedByUser( data.requestedByUser || null, {
            transaction,
        });
        
        await approval_requests.setApprovedByUser( data.approvedByUser || null, {
            transaction,
        });
        
        await approval_requests.setRejectedByUser( data.rejectedByUser || null, {
            transaction,
        });
        

        

        

        return approval_requests;
    }
    

    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_requestsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                requestType: item.requestType
            ||
            null
            ,
            
                entityId: item.entityId
            ||
            null
            ,
            
                entityType: item.entityType
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                requestedAt: item.requestedAt
            ||
            null
            ,
            
                approvedAt: item.approvedAt
            ||
            null
            ,
            
                rejectedAt: item.rejectedAt
            ||
            null
            ,
            
                rejectionReason: item.rejectionReason
            ||
            null
            ,
            
                amount: item.amount
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return approval_requests;
    }

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

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


        

        const updatePayload = {};
        
        if (data.requestType !== undefined) updatePayload.requestType = data.requestType;
        
        
        if (data.entityId !== undefined) updatePayload.entityId = data.entityId;
        
        
        if (data.entityType !== undefined) updatePayload.entityType = data.entityType;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.requestedAt !== undefined) updatePayload.requestedAt = data.requestedAt;
        
        
        if (data.approvedAt !== undefined) updatePayload.approvedAt = data.approvedAt;
        
        
        if (data.rejectedAt !== undefined) updatePayload.rejectedAt = data.rejectedAt;
        
        
        if (data.rejectionReason !== undefined) updatePayload.rejectionReason = data.rejectionReason;
        
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.requestedByUser !== undefined) {
            await approval_requests.setRequestedByUser(
              
              data.requestedByUser,
              
              { transaction }
            );
        }
        
        if (data.approvedByUser !== undefined) {
            await approval_requests.setApprovedByUser(
              
              data.approvedByUser,
              
              { transaction }
            );
        }
        
        if (data.rejectedByUser !== undefined) {
            await approval_requests.setRejectedByUser(
              
              data.rejectedByUser,
              
              { transaction }
            );
        }
        

        
        

        

        return approval_requests;
    }

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

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

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


        return approval_requests;
    }

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

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

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

        await approval_requests.destroy({
            transaction
        });

        return approval_requests;
    }

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

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

        if (!approval_requests) {
            return approval_requests;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.requestedByUser = await approval_requests.getRequestedByUser({
            transaction
        });
        
        
        output.approvedByUser = await approval_requests.getApprovedByUser({
            transaction
        });
        
        
        output.rejectedByUser = await approval_requests.getRejectedByUser({
            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.users,
        as: 'requestedByUser',
        
        where: filter.requestedByUser ? {
          [Op.or]: [
            { id: { [Op.in]: filter.requestedByUser.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.requestedByUser.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.entityId) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'approval_requests',
                        'entityId',
                        filter.entityId,
                    ),
                };
            }
            
            if (filter.entityType) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'approval_requests',
                        'entityType',
                        filter.entityType,
                    ),
                };
            }
            
            if (filter.rejectionReason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'approval_requests',
                        'rejectionReason',
                        filter.rejectionReason,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'approval_requests',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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


      

      

      



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

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

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

    
};

