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

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

        const voucher_approvals = await db.voucher_approvals.create(
            {
                id: data.id || undefined,
        
        acted_at: data.acted_at
        ||
        null
            ,
            
        decision: data.decision
        ||
        null
            ,
            
        comment: data.comment
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await voucher_approvals.setVoucher( data.voucher || null, {
            transaction,
        });
        
        await voucher_approvals.setWorkflow_step( data.workflow_step || null, {
            transaction,
        });
        
        await voucher_approvals.setActed_by_user( data.acted_by_user || null, {
            transaction,
        });
        

        

        

        return voucher_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 voucher_approvalsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                acted_at: item.acted_at
            ||
            null
            ,
            
                decision: item.decision
            ||
            null
            ,
            
                comment: item.comment
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return voucher_approvals;
    }

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

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


        

        const updatePayload = {};
        
        if (data.acted_at !== undefined) updatePayload.acted_at = data.acted_at;
        
        
        if (data.decision !== undefined) updatePayload.decision = data.decision;
        
        
        if (data.comment !== undefined) updatePayload.comment = data.comment;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.voucher !== undefined) {
            await voucher_approvals.setVoucher(
              
              data.voucher,
              
              { transaction }
            );
        }
        
        if (data.workflow_step !== undefined) {
            await voucher_approvals.setWorkflow_step(
              
              data.workflow_step,
              
              { transaction }
            );
        }
        
        if (data.acted_by_user !== undefined) {
            await voucher_approvals.setActed_by_user(
              
              data.acted_by_user,
              
              { transaction }
            );
        }
        

        
        

        

        return voucher_approvals;
    }

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

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

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


        return voucher_approvals;
    }

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

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

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

        await voucher_approvals.destroy({
            transaction
        });

        return voucher_approvals;
    }

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

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

        if (!voucher_approvals) {
            return voucher_approvals;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.voucher = await voucher_approvals.getVoucher({
            transaction
        });
        
        
        output.workflow_step = await voucher_approvals.getWorkflow_step({
            transaction
        });
        
        
        output.acted_by_user = await voucher_approvals.getActed_by_user({
            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.journal_vouchers,
        as: 'voucher',
        
        where: filter.voucher ? {
          [Op.or]: [
            { id: { [Op.in]: filter.voucher.split('|').map(term => Utils.uuid(term)) } },
            {
              voucher_number: {
                [Op.or]: filter.voucher.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.comment) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'voucher_approvals',
                        'comment',
                        filter.comment,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

      

      



            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.voucher_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, ) {
        let where = {};
        
        

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

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

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

    
};

