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

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

        const approval_tasks = await db.approval_tasks.create(
            {
                id: data.id || undefined,
        
        subject_type: data.subject_type
        ||
        null
            ,
            
        subject_reference: data.subject_reference
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        assigned_at: data.assigned_at
        ||
        null
            ,
            
        completed_at: data.completed_at
        ||
        null
            ,
            
        decision_comment: data.decision_comment
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await approval_tasks.setWorkflow( data.workflow || null, {
            transaction,
        });
        
        await approval_tasks.setStep( data.step || null, {
            transaction,
        });
        
        await approval_tasks.setAssignee( data.assignee || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.approval_tasks.getTableName(),
                belongsToColumn: 'evidence_files',
                belongsToId: approval_tasks.id,
            },
            data.evidence_files,
            options,
        );
        

        return approval_tasks;
    }
    

    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_tasksData = data.map((item, index) => ({
                id: item.id || undefined,
                
                subject_type: item.subject_type
            ||
            null
            ,
            
                subject_reference: item.subject_reference
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                assigned_at: item.assigned_at
            ||
            null
            ,
            
                completed_at: item.completed_at
            ||
            null
            ,
            
                decision_comment: item.decision_comment
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < approval_tasks.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.approval_tasks.getTableName(),
                    belongsToColumn: 'evidence_files',
                    belongsToId: approval_tasks[i].id,
                },
                data[i].evidence_files,
                options,
            );
        }
        

        return approval_tasks;
    }

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

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


        

        const updatePayload = {};
        
        if (data.subject_type !== undefined) updatePayload.subject_type = data.subject_type;
        
        
        if (data.subject_reference !== undefined) updatePayload.subject_reference = data.subject_reference;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.assigned_at !== undefined) updatePayload.assigned_at = data.assigned_at;
        
        
        if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
        
        
        if (data.decision_comment !== undefined) updatePayload.decision_comment = data.decision_comment;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.workflow !== undefined) {
            await approval_tasks.setWorkflow(
              
              data.workflow,
              
              { transaction }
            );
        }
        
        if (data.step !== undefined) {
            await approval_tasks.setStep(
              
              data.step,
              
              { transaction }
            );
        }
        
        if (data.assignee !== undefined) {
            await approval_tasks.setAssignee(
              
              data.assignee,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.approval_tasks.getTableName(),
                belongsToColumn: 'evidence_files',
                belongsToId: approval_tasks.id,
            },
            data.evidence_files,
            options,
        );
        

        return approval_tasks;
    }

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

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

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


        return approval_tasks;
    }

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

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

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

        await approval_tasks.destroy({
            transaction
        });

        return approval_tasks;
    }

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

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

        if (!approval_tasks) {
            return approval_tasks;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.workflow = await approval_tasks.getWorkflow({
            transaction
        });
        
        
        output.step = await approval_tasks.getStep({
            transaction
        });
        
        
        output.assignee = await approval_tasks.getAssignee({
            transaction
        });
        
        
        output.evidence_files = await approval_tasks.getEvidence_files({
            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.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)) } },
            {
              step_name: {
                [Op.or]: filter.step.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



      {
        model: db.file,
        as: 'evidence_files',
      },

    ];

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

            
            if (filter.subject_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'approval_tasks',
                        'subject_reference',
                        filter.subject_reference,
                    ),
                };
            }
            
            if (filter.decision_comment) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'approval_tasks',
                        'decision_comment',
                        filter.decision_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.completed_atRange) {
                const [start, end] = filter.completed_atRange;

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

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

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

            
            if (filter.subject_type) {
                where = {
                    ...where,
                subject_type: filter.subject_type,
            };
            }
            
            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_tasks.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_tasks',
                        'subject_reference',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

